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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
//! linear algebra module
//!
//! contains low level routines and the implementation of their corresponding
//! high level wrappers
//!
//! # memory allocation
//! since most `faer` crates aim to expose a low level api for optimal
//! performance, most algorithms try to defer memory allocation to the user
//!
//! however, since a lot of algorithms need some form of temporary space for
//! intermediate computations, they may ask for a slice of memory for that
//! purpose, by taking a [`stack: MemStack`](dyn_stack::MemStack) parameter. a
//! [`MemStack`] is a thin wrapper over a slice of memory bytes. this memory may
//! come from any valid source (heap allocation, fixed-size array on the stack,
//! etc.). the functions taking a [`MemStack`] parameter have a corresponding
//! function with a similar name ending in `_scratch` that returns the memory
//! requirements of the algorithm. for example:
//! [`householder::apply_block_householder_on_the_left_in_place_with_conj`] and
//! [`householder::apply_block_householder_on_the_left_in_place_scratch`]
//!
//! the memory stack may be reused in user-code to avoid repeated allocations,
//! and it is also possible to compute the sum ([`dyn_stack::StackReq::all_of`])
//! or union ([`dyn_stack::StackReq::any_of`]) of multiple scratch requirements,
//! in order to optimally combine them into a single allocation
//!
//! after computing a [`dyn_stack::StackReq`], one can query its layout to
//! allocate the required memory. the simplest way to do so is through
//! [`dyn_stack::MemBuffer::new`]
use crate::Shape;
use crate::internal_prelude::*;
use crate::mat::matown::align_for;
use crate::mat::{AsMatMut, MatMut};
use core::marker::PhantomData;
use dyn_stack::StackReq;
use colmat_traits::ComplexField;
/// returns the stack requirements for creating a temporary matrix with the
/// given dimensions.
pub fn temp_mat_scratch<T: ComplexField>(
	nrows: usize,
	ncols: usize,
) -> StackReq {
	let align = align_for(
		core::mem::size_of::<T>(),
		core::mem::align_of::<T>(),
		core::mem::needs_drop::<T>(),
	);
	let mut col_stride = nrows;
	if align > core::mem::size_of::<T>() {
		col_stride =
			col_stride.msrv_next_multiple_of(align / core::mem::size_of::<T>());
	}
	let len = col_stride.checked_mul(ncols).unwrap();
	StackReq::new_aligned::<T>(len, align)
}
/// Whether adapting a row-major input to a column-major copy pays for this shape.
///
/// The adaptation moves `nrows * ncols` elements contiguously twice and buys a
/// contiguous panel; on a small matrix the copy and the thread-region start-up
/// cost more than the strided panel they replace.
///
/// The floor is `64 * 64`, and it comes from the pair measured on 2026-10-19: at
/// `32 x 32` the copy cost 1.8x on `qr_factor` (row-major f64: 0.042 ms against
/// 0.024 ms at 8T), while at `64 x 64` and `96 x 96` removing it cost 1.10-1.31x
/// on the same family, and `lu`/`solve` were flat at both sizes. So the copy
/// pays from `4096` elements up and loses below it.
///
/// It is a floor on elements, not on a side, because the cost of the copy is the
/// area and the tall shapes the change was made for (`4096 x 256`, `1024 x 64`)
/// are asymmetric.
#[inline]
pub(crate) fn row_major_copy_pays(nrows: usize, ncols: usize) -> bool {
	nrows.saturating_mul(ncols) >= 64 * 64
}
/// The side of the tiles the layout copies move, and the unit a thread's share
/// of a copy is rounded to: 16 elements is a cache line or more for every
/// scalar the adaptation takes (`f32` is 64 bytes).
const COPY_TILE: usize = 16;
/// The working set, in bytes over both buffers, from which staging a layout
/// copy in [`COPY_TILE`] tiles pays.
///
/// It is the pair of buffers of a `512 x 512` f64 copy, `2 * 512 * 512 * 8`
/// bytes: the first cell of the table in `tensor4all/faer#323` where the tiled
/// path wins (`Llt::new` on a row-major input, -13.9%), while the cell just
/// below it (`511 x 511`, 4177936 bytes) still loses by 3.1-4.7%. That table is
/// the crossover, so the boundary follows the bytes copied and `size_of::<T>()`
/// rather than a side: an f32 copy of the same shape is half the working set
/// and crosses at `725 x 725` instead.
///
/// Raggedness is not an edge of it, whatever `tensor4all/faer#323` proposed: the
/// tile grid's remainder costs nothing measurable. `511`, `513` and `520`
/// (ragged) and `528`, `1008` and `1040` (`n % 16 == 0`) all lose to the
/// elementwise walk by the same 5.8-10.3% on `Llt::new` at 1T, and `512` and
/// `1024` win for the tiles because their row stride is a power of two, not
/// because they are aligned. What the tiles answer to below this byte count is
/// the strides, see [`TILE_COPY_POWER_OF_TWO_STRIDE_BYTES`].
///
/// Above it, what is not collected is the band where the walk is cheaper still:
/// `513`..`1040` on a host whose L3 does not hold the pair, where this host
/// measured 5.8-10.3% against the tiles (`1280` is a wash, `1536` wins for the
/// tiles again), because the byte count is pinned to the cache of the host
/// `tensor4all/faer#290` measured and a working set that fits a 16 MiB L3
/// domain still loses. Moving this constant is a separate change with its own
/// measurement on each host class.
const TILE_COPY_CACHE_BYTES: usize = 2 * 512 * 512 * 8;
#[cfg(test)]
std::thread_local! {
	static TILED_COPIES: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}
/// Test-only count of the copies [`copy_lower_across_layouts`] took in tiles on
/// the calling thread.
///
/// The function reports its choice to `MatMut::copy_from_triangular_lower`, but a
/// caller above that (`copy_from_triangular_upper`, and the QR/LQ
/// `copy_r`/`copy_l` routes through it) cannot see the return value, and a copy
/// that silently fell back produces the same values. Those routes read this
/// counter, so the path taken is asserted rather than inferred. It is per thread
/// because the test harness runs tests concurrently: a process-wide count would
/// let another test's tiled copy satisfy "tiled" and break "not tiled".
#[cfg(test)]
pub(crate) fn tiled_copies() -> usize {
	TILED_COPIES.with(|c| c.get())
}
/// The destination column stride, in bytes, above which a power-of-two stride
/// makes the tiles pay below [`TILE_COPY_CACHE_BYTES`] -- together with a
/// power-of-two source row stride, which is the stride this measurement found
/// to decide.
///
/// Measured on `tensor4all/faer#352` (evo, Zen5, `Llt::new` on a row-major f64
/// matrix, n swept 240..272): `256` is the only one of those n whose destination
/// column stride is a power of two (2048 bytes), and the only one where the
/// elementwise walk loses to the tiles: the walk takes 1.136x the tiles' time at
/// 1T and 1.157x at 8T, while at 248/252/260/264 (1984-2112 bytes) the walk
/// keeps 0.89-0.96x of the tiles'. That sweep moved the source's row stride
/// together with the destination's, so it could not say which of the two the
/// walk is stepping by.
///
/// `tensor4all/faer#323` separated them, on the copy alone (n = 511, 21 reps, 1T,
/// broccoli/Zen2, one process per cell, the strides set independently through
/// views): the tiles cost 380-402 us whatever the strides are, while the walk
/// costs 111-120 us unless the *source's row stride* is a power of two, where it
/// costs 1.47-1.49 ms (L1 set aliasing on the strided reads,
/// `PERFORMANCE_TIPS.md`). The destination's column stride moves nothing (2%
/// across the four cells). So the clause needs both, and this byte count is the
/// floor on the destination side only: the source side has no floor of its own,
/// and a source row stride below this one therefore does not keep a shape out of
/// the tiles by itself. The six-cell table is in
/// `docs/worklogs/2026-11-12-tiled-copy-source-stride.md`.
const TILE_COPY_POWER_OF_TWO_STRIDE_BYTES: usize = 2048;
/// Whether staging a `nrows x ncols` layout copy in [`COPY_TILE`] tiles pays,
/// for a source and a destination of `size_of::<T>()` bytes per element, a
/// destination column stride of `col_stride` elements and a source row stride of
/// `row_stride` elements.
///
/// Two boundaries are measured. The working set, [`TILE_COPY_CACHE_BYTES`]: the
/// f64 `512 x 512` pair is the first cell of `tensor4all/faer#323`'s table where
/// the tiles win, and the rest follows from that byte count and
/// `size_of::<T>()` -- `725 x 725` is the first square f32 shape at or above it,
/// at 4205000 bytes against 4194304, and that step is arithmetic, not a
/// measurement. The count is both buffers whole, so where `n > m` it is an upper
/// bound on what the copy touches: the copy stops at `min(m, n)` columns.
///
/// And the strides, when the destination column stride is a power of two at or
/// above [`TILE_COPY_POWER_OF_TWO_STRIDE_BYTES`] **and** the source row stride is
/// a power of two: measured cells with such a pair run faster with the tiles
/// although their working set is small, and the destination side alone is not
/// enough (the table above). Both are byte counts, so the clause follows
/// `size_of::<T>()` the way the working-set gate does.
///
/// The source side is what a padded destination makes load-bearing: an owned
/// f64 matrix rounds its column stride up to a multiple of 8 rows
/// (`matown::align_for`), so `505 x 505` has a 512-column (4096-byte)
/// destination stride, a power of two, while its source row stride is 4040 bytes
/// and not one. `505`..`511` took the tiles on the destination stride alone and
/// lost 8-12% of `Llt::new` to the walk there (`tensor4all/faer#323`); `512`,
/// with both strides at 4096 bytes, keeps the tiles.
#[inline]
fn tile_copy_pays<T>(
	nrows: usize,
	ncols: usize,
	col_stride: isize,
	row_stride: isize,
) -> bool {
	if nrows
		.saturating_mul(ncols)
		.saturating_mul(2 * core::mem::size_of::<T>())
		>= TILE_COPY_CACHE_BYTES
	{
		return true;
	}
	let size = core::mem::size_of::<T>();
	let col_stride_bytes = col_stride.unsigned_abs().saturating_mul(size);
	let row_stride_bytes = row_stride.unsigned_abs().saturating_mul(size);
	col_stride_bytes.is_power_of_two()
		&& col_stride_bytes >= TILE_COPY_POWER_OF_TWO_STRIDE_BYTES
		&& row_stride_bytes.is_power_of_two()
}
/// How a copy over `lines` lines of the destination's major dimension is shared
/// between at most `degree` threads: `(lines per task, tasks)`, each share a
/// whole number of tiles except the last.
fn copy_tasks(lines: usize, degree: usize) -> (usize, usize) {
	let tiles = lines.div_ceil(COPY_TILE);
	let n_tasks = Ord::min(degree, tiles).max(1);
	let chunk = tiles.div_ceil(n_tasks) * COPY_TILE;
	(chunk, lines.div_ceil(chunk.max(1)))
}
/// Copies `src` into `dst` elementwise, where the two have transposed strides:
/// one is column-major, the other row-major, over the same shape, in tiles.
///
/// With a parallel `par` the copy is split along the destination's major
/// dimension -- rows when `dst` is row-major, columns when it is column-major --
/// in whole tiles, so each thread writes whole contiguous lines of its own and
/// two threads meet in a cache line only at the edge of their shares (the
/// destination's base need not be aligned). A split along the other dimension
/// gives a thread a few elements of every line, and on a narrow matrix several
/// threads write the same line (`1024 x 64` on 64 threads: one column each,
/// eight threads per line of the row-major side).
pub(crate) fn copy_across_layouts<T: ComplexField>(
	mut dst: MatMut<'_, T>,
	src: MatRef<'_, T>,
	par: Par,
) {
	#[cfg(feature = "rayon")]
	{
		use rayon::prelude::*;
		let dst_row_major = dst.row_stride().unsigned_abs() != 1;
		let lines = if dst_row_major { dst.nrows() } else { dst.ncols() };
		let (chunk, n_tasks) =
			copy_tasks(lines, crate::utils::thread::parallelism_degree(&par));
		if n_tasks > 1 {
			if dst_row_major {
				crate::utils::thread::for_each(
					par,
					n_tasks,
					dst.rb_mut()
						.par_row_chunks_mut(chunk)
						.zip_eq(src.par_row_chunks(chunk)),
					|(mut d, s)| copy_across_layouts_block(d.rb_mut(), s),
				);
			} else {
				crate::utils::thread::for_each(
					par,
					n_tasks,
					dst.rb_mut()
						.par_col_chunks_mut(chunk)
						.zip_eq(src.par_col_chunks(chunk)),
					|(mut d, s)| copy_across_layouts_block(d.rb_mut(), s),
				);
			}
			return;
		}
	}
	let _ = par;
	copy_across_layouts_block(dst.rb_mut(), src);
}
/// the phase $d / |d|$ that makes a triangular factor's diagonal entry real
/// positive, and `1` for an exactly zero entry (where the phase is arbitrary and
/// the factorization keeps the raw sign).
#[inline]
pub(crate) fn positive_phase<T: ComplexField>(d: T) -> T {
	let abs = d.abs();
	if abs == zero() {
		one()
	} else {
		d.mul_real(abs.recip())
	}
}
/// A column-major copy of the row-major `src`, in a new buffer of
/// `nrows * ncols` elements (column stride `nrows`): the work matrix of the
/// row-major adaptations.
///
/// The buffer is allocated uninitialised and each thread initialises its own
/// columns -- zeros, then the copy over them -- so the pages are first touched
/// by the threads that copy into them rather than all by the caller, and the
/// initialisation runs in parallel instead of as a serial pass before the copy.
/// The split is [`copy_across_layouts`]'s, over the buffer's columns.
pub(crate) fn column_major_copy<T: ComplexField>(
	src: MatRef<'_, T>,
	par: Par,
) -> alloc::vec::Vec<T> {
	let (m, n) = src.shape();
	let len = m.checked_mul(n).unwrap();
	let mut buf = alloc::vec::Vec::<T>::with_capacity(len);
	let base = SendPtr(buf.as_mut_ptr());
	// Initialises columns `j0..j1` of the buffer. Every task touches a disjoint
	// range of the allocation; nothing reads an element before this writes it,
	// and the view over the range is formed only once it is initialised. A
	// panic leaves `buf` at length zero, which leaks the elements written so far
	// and drops none.
	let fill = |j0: usize, j1: usize| unsafe {
		let ptr = base.get().add(j0 * m);
		for k in 0..(j1 - j0) * m {
			ptr.add(k).write(zero::<T>());
		}
		copy_across_layouts_block(
			MatMut::from_raw_parts_mut(ptr, m, j1 - j0, 1, m as isize),
			src.subcols(j0, j1 - j0),
		);
	};
	#[cfg(feature = "rayon")]
	{
		let (chunk, n_tasks) =
			copy_tasks(n, crate::utils::thread::parallelism_degree(&par));
		if n_tasks > 1 {
			crate::utils::thread::for_each(
				par,
				n_tasks,
				rayon::iter::IntoParallelIterator::into_par_iter(0..n_tasks),
				|t| fill(t * chunk, Ord::min((t + 1) * chunk, n)),
			);
			unsafe { buf.set_len(len) };
			return buf;
		}
	}
	let _ = par;
	fill(0, n);
	unsafe { buf.set_len(len) };
	buf
}
/// The base of [`column_major_copy`]'s buffer, handed to the threads that
/// initialise disjoint ranges of it.
struct SendPtr<T>(*mut T);
impl<T> Clone for SendPtr<T> {
	fn clone(&self) -> Self {
		*self
	}
}
impl<T> Copy for SendPtr<T> {}
unsafe impl<T: Send> Send for SendPtr<T> {}
unsafe impl<T: Send> Sync for SendPtr<T> {}
impl<T> SendPtr<T> {
	// a method, so the closures capture the wrapper and not the raw field
	fn get(self) -> *mut T {
		self.0
	}
}
/// One `16 x 16` tile of the copy, on one thread: read the tile along whichever
/// side is row-major and write it along whichever is column-major, so neither
/// side steps by the other's row stride. Each source value is cloned into an
/// `Option` tile and moved into the destination, without another clone or a
/// seed value. Every slot the second loop reads was written by the first.
fn copy_across_layouts_block<T: Clone>(
	mut dst: MatMut<'_, T>,
	src: MatRef<'_, T>,
) {
	const B: usize = COPY_TILE;
	let (m, n) = dst.shape();
	// `src` row-major means `dst` is the column-major one, and the other way
	// round; exactly one of the two holds.
	let src_row_major = src.row_stride().unsigned_abs() != 1;
	let mut tile: [Option<T>; B * B] = core::array::from_fn(|_| None);
	let mut jb = 0;
	while jb < n {
		let j1 = Ord::min(jb + B, n);
		let mut ib = 0;
		while ib < m {
			let i1 = Ord::min(ib + B, m);
			if src_row_major {
				for i in ib..i1 {
					for j in jb..j1 {
						tile[(i - ib) * B + (j - jb)] =
							Some(src[(i, j)].clone());
					}
				}
				for j in jb..j1 {
					for i in ib..i1 {
						dst[(i, j)] =
							tile[(i - ib) * B + (j - jb)].take().unwrap();
					}
				}
			} else {
				for j in jb..j1 {
					for i in ib..i1 {
						tile[(i - ib) * B + (j - jb)] =
							Some(src[(i, j)].clone());
					}
				}
				for i in ib..i1 {
					for j in jb..j1 {
						dst[(i, j)] =
							tile[(i - ib) * B + (j - jb)].take().unwrap();
					}
				}
			}
			ib += B;
		}
		jb += B;
	}
}
/// Copies the lower triangle of `src`, diagonal included, into `dst` in tiles,
/// when `dst` is column-major, `src` is not, and [`tile_copy_pays`] holds for the
/// working set and the destination's column stride; returns `false` and touches
/// nothing otherwise.
/// The elements written are exactly those
/// `MatMut::copy_from_triangular_lower` writes (column `j < min(m, n)`, rows
/// `j..m`), so the upper triangle of `dst` is left as it was.
///
/// The elementwise path walks `dst` column by column, so for a row-major `src`
/// every read steps by the source's row stride: at `1024 x 1024` f64 that is
/// 4.2 ms against 0.30 ms from a column-major source, and it is the whole of
/// the gap between the two orders of `Llt::new`. Each `16`-column band is the
/// diagonal tile, copied elementwise below its diagonal, and the rectangle
/// under it, copied with [`copy_across_layouts_block`].
pub(crate) fn copy_lower_across_layouts<T: Clone>(
	mut dst: MatMut<'_, T>,
	src: MatRef<'_, T>,
) -> bool {
	let (m, n) = dst.shape();
	if dst.row_stride() != 1
		|| src.row_stride().unsigned_abs() == 1
		|| !tile_copy_pays::<T>(m, n, dst.col_stride(), src.row_stride())
	{
		return false;
	}
	let k = Ord::min(m, n);
	let mut jb = 0;
	while jb < k {
		let j1 = Ord::min(jb + COPY_TILE, k);
		for j in jb..j1 {
			for i in j..j1 {
				dst[(i, j)] = src[(i, j)].clone();
			}
		}
		if j1 < m {
			copy_across_layouts_block(
				dst.rb_mut().submatrix_mut(j1, jb, m - j1, j1 - jb),
				src.submatrix(j1, jb, m - j1, j1 - jb),
			);
		}
		jb = j1;
	}
	#[cfg(test)]
	TILED_COPIES.with(|c| c.set(c.get() + 1));
	true
}
struct DynMat<'a, T: ComplexField, Rows: Shape, Cols: Shape> {
	ptr: *mut T,
	nrows: Rows,
	ncols: Cols,
	col_stride: usize,
	__marker: PhantomData<(&'a T, T)>,
}
impl<'a, T: ComplexField, Rows: Shape, Cols: Shape> Drop
	for DynMat<'a, T, Rows, Cols>
{
	#[inline]
	fn drop(&mut self) {
		unsafe {
			core::ptr::drop_in_place(core::slice::from_raw_parts_mut(
				self.ptr,
				self.col_stride * self.ncols.unbound(),
			))
		};
	}
}
impl<'a, T: ComplexField, Rows: Shape, Cols: Shape> AsMatRef
	for DynMat<'a, T, Rows, Cols>
{
	type Cols = Cols;
	type Owned = Mat<T, Rows, Cols>;
	type Rows = Rows;
	type T = T;

	fn as_mat_ref(&self) -> crate::mat::MatRef<'_, T, Rows, Cols> {
		unsafe {
			MatRef::from_raw_parts(
				self.ptr as *const T,
				self.nrows,
				self.ncols,
				1,
				self.col_stride as isize,
			)
		}
	}
}
impl<'a, T: ComplexField, Rows: Shape, Cols: Shape> AsMatMut
	for DynMat<'a, T, Rows, Cols>
{
	fn as_mat_mut(&mut self) -> crate::mat::MatMut<'_, T, Rows, Cols> {
		unsafe {
			MatMut::from_raw_parts_mut(
				self.ptr,
				self.nrows,
				self.ncols,
				1,
				self.col_stride as isize,
			)
		}
	}
}
struct DropGuard<T> {
	ptr: *mut T,
	len: usize,
}
impl<T> Drop for DropGuard<T> {
	#[inline]
	fn drop(&mut self) {
		unsafe {
			core::ptr::drop_in_place(core::slice::from_raw_parts_mut(
				self.ptr, self.len,
			))
		};
	}
}
/// creates a temporary matrix of uninit values, from the given memory stack.
#[track_caller]
pub unsafe fn temp_mat_uninit<
	'a,
	T: ComplexField + 'a,
	Rows: Shape + 'a,
	Cols: Shape + 'a,
>(
	nrows: Rows,
	ncols: Cols,
	stack: &'a mut MemStack,
) -> (
	impl 'a + AsMatMut<T = T, Rows = Rows, Cols = Cols>,
	&'a mut MemStack,
) {
	let align = align_for(
		core::mem::size_of::<T>(),
		core::mem::align_of::<T>(),
		core::mem::needs_drop::<T>(),
	);
	let mut col_stride = nrows.unbound();
	if align > core::mem::size_of::<T>() {
		col_stride =
			col_stride.msrv_next_multiple_of(align / core::mem::size_of::<T>());
	}
	let len = col_stride.checked_mul(ncols.unbound()).unwrap();
	let (uninit, stack) = stack.make_aligned_uninit::<T>(len, align);
	let ptr = uninit.as_mut_ptr() as *mut T;
	if core::mem::needs_drop::<T>() {
		unsafe {
			let mut guard = DropGuard { ptr, len: 0 };
			for j in 0..len {
				let ptr = ptr.add(j);
				let val = T::nan_impl();
				ptr.write(val);
				guard.len += 1;
			}
			core::mem::forget(guard);
		}
	}
	(
		DynMat {
			ptr,
			nrows,
			ncols,
			col_stride,
			__marker: PhantomData,
		},
		stack,
	)
}
/// creates a temporary matrix of zero values, from the given memory stack.
#[track_caller]
pub fn temp_mat_zeroed<
	'a,
	T: ComplexField + 'a,
	Rows: Shape + 'a,
	Cols: Shape + 'a,
>(
	nrows: Rows,
	ncols: Cols,
	stack: &'a mut MemStack,
) -> (
	impl 'a + AsMatMut<T = T, Rows = Rows, Cols = Cols>,
	&'a mut MemStack,
) {
	let align = align_for(
		core::mem::size_of::<T>(),
		core::mem::align_of::<T>(),
		core::mem::needs_drop::<T>(),
	);
	let mut col_stride = nrows.unbound();
	if align > core::mem::size_of::<T>() {
		col_stride =
			col_stride.msrv_next_multiple_of(align / core::mem::size_of::<T>());
	}
	let len = col_stride.checked_mul(ncols.unbound()).unwrap();
	_ = stack.make_aligned_uninit::<T>(len, align);
	let (uninit, stack) = stack.make_aligned_uninit::<T>(len, align);
	let ptr = uninit.as_mut_ptr() as *mut T;
	unsafe {
		let mut guard = DropGuard { ptr, len: 0 };
		for j in 0..len {
			let ptr = ptr.add(j);
			let val = T::zero_impl();
			ptr.write(val);
			guard.len += 1;
		}
		core::mem::forget(guard);
	}
	(
		DynMat {
			ptr,
			nrows,
			ncols,
			col_stride,
			__marker: PhantomData,
		},
		stack,
	)
}
pub mod cholesky;
pub mod evd;
pub mod gevd;
pub mod householder;
/// jacobi rotation matrix
pub mod jacobi;
/// kronecker product
pub mod kron;
pub mod lq;
pub mod lu;
mod mat_ops;
pub mod matmul;
pub mod pfaffian;
pub mod qr;
pub(crate) mod reductions;
/// high level solvers
pub mod solvers;
pub mod svd;
/// triangular matrix inverse
pub mod triangular_inverse;
/// triangular matrix solve
pub mod triangular_solve;
/// matrix zipping implementation
pub mod zip;
#[cfg(test)]
mod tests {
	use super::*;
	use dyn_stack::MemBuffer;

	/// A scalar the fixture can build and two results can be compared with
	/// exactly -- exact because every entry point below runs the same arithmetic
	/// on the same values once the copy has happened.
	trait Entry: ComplexField {
		fn at(i: usize, j: usize) -> Self;
		fn same(&self, other: &Self) -> bool;
		fn close(&self, other: &Self) -> bool;
	}
	impl Entry for f64 {
		fn at(i: usize, j: usize) -> Self {
			val(i, j)
		}
		fn same(&self, other: &Self) -> bool {
			self.to_bits() == other.to_bits()
		}
		fn close(&self, other: &Self) -> bool {
			// `inf` marks an unused diagonal entry and must compare equal to
			// itself; subtraction would make it `NaN`.
			if self.same(other) {
				return true;
			}
			(self - other).abs() <= 1e-10 * self.abs().max(other.abs()).max(1.0)
		}
	}
	impl Entry for crate::c64 {
		fn at(i: usize, j: usize) -> Self {
			crate::c64::new(val(i, j), val(i + 7, j + 3))
		}
		fn same(&self, other: &Self) -> bool {
			self.re.to_bits() == other.re.to_bits()
				&& self.im.to_bits() == other.im.to_bits()
		}
		fn close(&self, other: &Self) -> bool {
			if self.same(other) {
				return true;
			}
			(self.re - other.re).abs()
				<= 1e-10 * self.re.abs().max(other.re.abs()).max(1.0)
				&& (self.im - other.im).abs()
					<= 1e-10 * self.im.abs().max(other.im.abs()).max(1.0)
		}
	}
	/// A well-conditioned fixture with no structure for the two layouts to
	/// exploit: a `(i, j)`-hashed value in `[-5, 5)`.
	fn val(i: usize, j: usize) -> f64 {
		let mut h = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
			^ (j as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
		h ^= h >> 31;
		h = h.wrapping_mul(0x94D0_49BB_1331_11EB);
		h ^= h >> 29;
		((h >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 10.0
	}
	/// Everything the factorization left behind, as stored: the factor at every
	/// `(i, j)`, then each array it wrote, entry by entry.
	fn compare<T: Entry>(what: &str, cm: &[T], rm: &[T]) {
		if cm.len() != rm.len() {
			panic!("{what}: {} entries against {}", cm.len(), rm.len());
		}
		for k in 0..cm.len() {
			if !cm[k].same(&rm[k]) {
				panic!("{what}: entry {k} differs between the two orders");
			}
		}
	}
	fn same_exact<T: Entry>(what: &str, cm: &[T], rm: &[T]) {
		compare(what, cm, rm);
	}
	/// The `tau` array follows the factor: identical above the copy floor, equal
	/// up to rounding below it, where the row-major side factors in place.
	fn same_tau<T: Entry>(m: usize, n: usize, what: &str, cm: &[T], rm: &[T]) {
		if crate::linalg::row_major_copy_pays(m, n) {
			compare(what, cm, rm);
			return;
		}
		if cm.len() != rm.len() {
			panic!("{what}: {} entries against {}", cm.len(), rm.len());
		}
		for k in 0..cm.len() {
			if !cm[k].close(&rm[k]) {
				panic!("{what}: entry {k} differs between the two orders");
			}
		}
	}
	fn same_index<T: PartialEq + core::fmt::Debug + Copy>(
		what: &str,
		cm: &[T],
		rm: &[T],
	) {
		if cm != rm {
			panic!("{what}: {cm:?} against {rm:?}");
		}
	}
	/// The same matrix, flat in each order: `cm` column-major, `rm` row-major.
	/// `flipped` builds both so that a view whose rows are walked backwards
	/// represents the same matrix in each -- the row-major view is read from its
	/// last row with a negative row stride.
	fn fixture<T: Entry>(m: usize, n: usize, flipped: bool) -> (Vec<T>, Vec<T>) {
		let flipped = flipped && m > 0 && n > 0;
		let row_of = |i: usize| if flipped { m - 1 - i } else { i };
		let mut cm = Vec::with_capacity(m * n);
		for j in 0..n {
			for i in 0..m {
				cm.push(T::at(row_of(i), j));
			}
		}
		let mut rm = Vec::with_capacity(m * n);
		for i in 0..m {
			for j in 0..n {
				rm.push(T::at(i, j));
			}
		}
		(cm, rm)
	}
	/// The row-major side's flat position for a factor entry read through a
	/// `flipped` view: the view's row `i` is storage row `m - 1 - i`.
	fn rm_strides(m: usize, n: usize, flipped: bool) -> (usize, isize, isize) {
		if flipped && m > 0 && n > 0 {
			((m - 1) * n, -(n as isize), 1)
		} else {
			(0, n as isize, 1)
		}
	}
	fn compare_row_major<T: Entry>(
		m: usize,
		n: usize,
		flipped: bool,
		what: &str,
		cm: &[T],
		rm: &[T],
	) {
		// Above the copy floor both orders take the same arithmetic and must
		// agree bit for bit; below it the row-major side factors in place
		// through a strided panel, which is the same matrix but a different
		// summation order.
		let exact = crate::linalg::row_major_copy_pays(m, n);
		compare_row_major_exact_if(m, n, flipped, what, cm, rm, exact);
	}
	/// [`compare_row_major`] with the exactness given by the caller, for an entry
	/// point whose own guard decides when the copy is taken.
	fn compare_row_major_exact_if<T: Entry>(
		m: usize,
		n: usize,
		flipped: bool,
		what: &str,
		cm: &[T],
		rm: &[T],
		exact: bool,
	) {
		let flipped = flipped && m > 0 && n > 0;
		for j in 0..n {
			for i in 0..m {
				let k = if flipped { m - 1 - i } else { i };
				let (a, b) = (cm[i + j * m].clone(), rm[k * n + j].clone());
				if !(if exact { a.same(&b) } else { a.close(&b) }) {
					panic!(
						"{what} {m}x{n}: entry ({i}, {j}) differs between the two orders"
					);
				}
			}
		}
	}

	/// Every entry point that adapts a row-major matrix to a column-major one has
	/// to leave behind the column-major factorization of the same matrix: same
	/// factor, same `tau` matrix, same permutations, same transposition count.
	/// This is what says so, for the column-pivoted QR and both LU flavours (the
	/// no-pivoting QR has its own test beside its `qr_in_place`, with the shapes
	/// its guard leaves alone). Each shape is run with a plain row-major view and
	/// with one whose rows are walked backwards, so the copy's own direction
	/// branch is covered on a negative stride too.
	#[test]
	fn test_row_major_adaptation_matches_the_column_major_one() {
		use crate::linalg::lu::full_pivoting::factor as flu;
		use crate::linalg::lu::partial_pivoting::factor as plu;
		use crate::linalg::qr::col_pivoting::factor as cpqr;

		fn check_cpqr<T: Entry>(m: usize, n: usize, flipped: bool, mut par: Par) {
			let size = Ord::min(m, n);
			let bs = cpqr::recommended_block_size::<T>(m, n);
			let scratch =
				cpqr::qr_in_place_scratch::<usize, T>(m, n, bs, par.shape(), default());
			let (mut cm, mut rm) = fixture::<T>(m, n, flipped);
			let mut h_cm = vec![T::zero(); bs * size];
			let mut h_rm = vec![T::zero(); bs * size];
			let mut p_cm = vec![0usize; n];
			let mut p_rm = vec![0usize; n];
			let mut pi_cm = vec![0usize; n];
			let mut pi_rm = vec![0usize; n];
			let mut run = |a: &mut [T],
			           h: &mut [T],
			           p: &mut [usize],
			           pi: &mut [usize],
			           (base, rs, cs): (usize, isize, isize)|
			 -> cpqr::ColPivQrInfo {
				unsafe {
					cpqr::qr_in_place(
						MatMut::from_raw_parts_mut(
							a.as_mut_ptr().add(base),
							m,
							n,
							rs,
							cs,
						),
						MatMut::from_raw_parts_mut(
							h.as_mut_ptr(),
							bs,
							size,
							1,
							bs as isize,
						),
						p,
						pi,
						par.reborrow(),
						MemStack::new(&mut MemBuffer::new(scratch)),
						default(),
					)
					.0
				}
			};
			let cm_info = run(&mut cm, &mut h_cm, &mut p_cm, &mut pi_cm, (0, 1, m as isize));
			let rm_info = run(
				&mut rm,
				&mut h_rm,
				&mut p_rm,
				&mut pi_rm,
				rm_strides(m, n, flipped),
			);
			compare_row_major(m, n, flipped, "col_pivoting qr", &cm, &rm);
			same_tau(m, n, "col_pivoting qr tau", &h_cm, &h_rm);
			same_index("col_pivoting qr perm", &p_cm, &p_rm);
			same_index("col_pivoting qr perm inv", &pi_cm, &pi_rm);
			same_index(
				"col_pivoting qr transpositions",
				&[cm_info.transposition_count],
				&[rm_info.transposition_count],
			);
		}

		fn check_plu<T: Entry>(m: usize, n: usize, flipped: bool, mut par: Par) {
			let scratch = plu::lu_in_place_scratch::<usize, T>(m, n, par.shape(), default());
			let (mut cm, mut rm) = fixture::<T>(m, n, flipped);
			let mut p_cm = vec![0usize; m];
			let mut p_rm = vec![0usize; m];
			let mut pi_cm = vec![0usize; m];
			let mut pi_rm = vec![0usize; m];
			let mut run = |a: &mut [T],
			           p: &mut [usize],
			           pi: &mut [usize],
			           (base, rs, cs): (usize, isize, isize)|
			 -> plu::PartialPivLuInfo {
				unsafe {
					plu::lu_in_place(
						MatMut::from_raw_parts_mut(
							a.as_mut_ptr().add(base),
							m,
							n,
							rs,
							cs,
						),
						p,
						pi,
						par.reborrow(),
						MemStack::new(&mut MemBuffer::new(scratch)),
						default(),
					)
					.0
				}
			};
			let cm_info = run(&mut cm, &mut p_cm, &mut pi_cm, (0, 1, m as isize));
			let rm_info =
				run(&mut rm, &mut p_rm, &mut pi_rm, rm_strides(m, n, flipped));
			// bit for bit where the copy is taken; a row-major view (`|col_stride|
			// = 1`) is otherwise factored in place (tensor4all/faer#314): its leaf is
			// the column-major leaf on a copy of the panel, but the trailing
			// solves and products take the row-major operands as they are and need
			// not round the same way (observed: `f64` bit for bit, `c64` not)
			compare_row_major_exact_if(
				m,
				n,
				flipped,
				"partial pivoting lu",
				&cm,
				&rm,
				{
					let (_, rs, cs) = rm_strides(m, n, flipped);
					plu::takes_the_copy(m, n, rs, cs, par.degree())
				},
			);
			same_index("partial pivoting lu perm", &p_cm, &p_rm);
			same_index("partial pivoting lu perm inv", &pi_cm, &pi_rm);
			same_index(
				"partial pivoting lu transpositions",
				&[cm_info.transposition_count],
				&[rm_info.transposition_count],
			);
		}

		fn check_flu<T: Entry>(m: usize, n: usize, flipped: bool, mut par: Par) {
			let scratch = flu::lu_in_place_scratch::<usize, T>(m, n, par.shape(), default());
			let (mut cm, mut rm) = fixture::<T>(m, n, flipped);
			let mut p_cm = vec![0usize; m];
			let mut p_rm = vec![0usize; m];
			let mut pi_cm = vec![0usize; m];
			let mut pi_rm = vec![0usize; m];
			let mut c_cm = vec![0usize; n];
			let mut c_rm = vec![0usize; n];
			let mut ci_cm = vec![0usize; n];
			let mut ci_rm = vec![0usize; n];
			let mut run = |a: &mut [T],
			           p: &mut [usize],
			           pi: &mut [usize],
			           c: &mut [usize],
			           ci: &mut [usize],
			           (base, rs, cs): (usize, isize, isize)|
			 -> flu::FullPivLuInfo {
				unsafe {
					flu::lu_in_place(
						MatMut::from_raw_parts_mut(
							a.as_mut_ptr().add(base),
							m,
							n,
							rs,
							cs,
						),
						p,
						pi,
						c,
						ci,
						par.reborrow(),
						MemStack::new(&mut MemBuffer::new(scratch)),
						default(),
					)
					.0
				}
			};
			let cm_info =
				run(&mut cm, &mut p_cm, &mut pi_cm, &mut c_cm, &mut ci_cm, (0, 1, m as isize));
			let rm_info = run(
				&mut rm,
				&mut p_rm,
				&mut pi_rm,
				&mut c_rm,
				&mut ci_rm,
				rm_strides(m, n, flipped),
			);
			// bit for bit where the copy is taken; the square shapes below 128 go
			// through the transpose dual instead, the complex products in another
			// order. The dual breaks a magnitude tie by the smallest row first, the
			// column-major search by the smallest column (`lu_in_place`, "Pivot
			// ties"), so the pivots agree here only because this fixture does not
			// hit such a tie; `full_piv_lu_row_major_no_copy` pins one where the
			// two orders part.
			compare_row_major_exact_if(
				m,
				n,
				flipped,
				"full pivoting lu",
				&cm,
				&rm,
				{
					let (_, rs, cs) = rm_strides(m, n, flipped);
					flu::row_major_takes_the_copy(m, n, rs, cs)
				},
			);
			same_index("full pivoting lu row perm", &p_cm, &p_rm);
			same_index("full pivoting lu row perm inv", &pi_cm, &pi_rm);
			same_index("full pivoting lu col perm", &c_cm, &c_rm);
			same_index("full pivoting lu col perm inv", &ci_cm, &ci_rm);
			same_index(
				"full pivoting lu transpositions",
				&[cm_info.transposition_count],
				&[rm_info.transposition_count],
			);
		}

		for (m, n) in [
			(1, 1),
			(2, 2),
			(16, 16),
			(17, 15),
			(64, 64),
			(300, 17),
			(64, 256),
			(300, 8),
		] {
			for flipped in [false, true] {
				let run = |mut par: Par<'_>| {
					check_cpqr::<f64>(m, n, flipped, par.reborrow());
					check_cpqr::<crate::c64>(m, n, flipped, par);
				};
				run(Par::Seq);
				crate::team::with_team(8, |par| run(par));
			}
		}
		for (m, n) in [
			(1, 1),
			(2, 2),
			(16, 16),
			(17, 15),
			(64, 64),
			(127, 127),
			(128, 128),
			(300, 17),
		] {
			for flipped in [false, true] {
				let run = |mut par: Par<'_>| {
					check_plu::<f64>(m, n, flipped, par.reborrow());
					check_plu::<crate::c64>(m, n, flipped, par.reborrow());
					check_flu::<f64>(m, n, flipped, par.reborrow());
					check_flu::<crate::c64>(m, n, flipped, par);
				};
				run(Par::Seq);
				crate::team::with_team(8, |par| run(par));
			}
		}
	}

	/// Each share of a layout copy is a whole number of tiles except the last,
	/// the shares cover the lines exactly, and there are never more than the
	/// threads or the tiles.
	#[test]
	fn test_copy_tasks_cover_the_lines_in_whole_tiles() {
		for lines in [0usize, 1, 15, 16, 17, 64, 100, 256, 1000, 4096] {
			for degree in [1usize, 2, 3, 8, 64, 1000] {
				let (chunk, n_tasks) = copy_tasks(lines, degree);
				core::assert!(n_tasks <= Ord::max(degree, 1));
				core::assert!(n_tasks <= lines.div_ceil(COPY_TILE));
				assert_eq!(chunk % COPY_TILE, 0, "{lines} lines on {degree}");
				if lines > 0 {
					core::assert!(chunk * n_tasks >= lines);
					core::assert!(chunk * (n_tasks - 1) < lines);
				}
			}
		}
	}

	/// The copy in both directions, on every split the teams below give it
	/// (shares of whole tiles over odd shapes, more threads than tiles, a single
	/// line), with a reversed row-major view: every entry lands where it
	/// belongs. `column_major_copy` is the same check on a buffer it allocates
	/// and initialises itself.
	#[test]
	fn test_layout_copies_on_a_team() {
		fn check<T: Entry>(m: usize, n: usize, flipped: bool, mut par: Par) {
			let (cm, rm) = fixture::<T>(m, n, flipped);
			let (base, rs, cs) = rm_strides(m, n, flipped);
			let row_major = unsafe {
				MatRef::from_raw_parts(rm.as_ptr().add(base), m, n, rs, cs)
			};
			let col_major = MatRef::from_column_major_slice(&cm, m, n);

			let work = column_major_copy(row_major, par.reborrow());
			same_exact("column_major_copy", &cm, &work);

			let mut cm_out = vec![T::zero(); m * n];
			copy_across_layouts(
				MatMut::from_column_major_slice_mut(&mut cm_out, m, n),
				row_major,
				par.reborrow(),
			);
			same_exact("to column-major", &cm, &cm_out);

			let mut rm_out = vec![T::zero(); m * n];
			let rm_view = unsafe {
				MatMut::from_raw_parts_mut(
					rm_out.as_mut_ptr().add(base),
					m,
					n,
					rs,
					cs,
				)
			};
			copy_across_layouts(rm_view, col_major, par);
			same_exact("to row-major", &rm, &rm_out);
		}
		for (m, n) in [
			(0, 0),
			(0, 5),
			(5, 0),
			(1, 1),
			(1, 70),
			(70, 1),
			(17, 15),
			(33, 100),
			(100, 33),
			(300, 17),
		] {
			for flipped in [false, true] {
				let run = |mut par: Par<'_>| {
					check::<f64>(m, n, flipped, par.reborrow());
					check::<crate::c64>(m, n, flipped, par);
				};
				run(Par::Seq);
				for threads in [2, 3, 8] {
					crate::team::with_team(threads, |par| run(par));
				}
			}
		}
	}

	/// The tiled path of `copy_from_triangular_lower` writes exactly the
	/// elements the elementwise one does, with the same values, and leaves the
	/// rest of the destination alone. The shapes above the threshold run the
	/// tiles; the ones below it run the elementwise walk, which the same check
	/// covers: square, tall, wide, a narrow band, sides that are not a multiple
	/// of the tile, and a source whose rows are walked backwards.
	#[test]
	fn tiled_triangular_copy_writes_what_the_elementwise_one_does() {
		fn check<T: Entry>(m: usize, n: usize, flipped: bool, tiled: bool) {
			let (_, rm) = fixture::<T>(m, n, flipped);
			let (base, rs, cs) = rm_strides(m, n, flipped);
			let src = unsafe {
				MatRef::from_raw_parts(rm.as_ptr().add(base), m, n, rs, cs)
			};
			let sentinel = T::at(m + 11, n + 13);
			let mut out = Mat::<T>::from_fn(m, n, |_, _| sentinel.clone());
			assert_eq!(
				tile_copy_pays::<T>(m, n, out.col_stride(), src.row_stride()),
				tiled
			);
			out.copy_from_triangular_lower(src);
			for j in 0..n {
				for i in 0..m {
					let want = if i >= j { src[(i, j)].clone() } else { sentinel.clone() };
					if !out[(i, j)].same(&want) {
						panic!("{m}x{n} flipped={flipped}: entry ({i}, {j}) differs");
					}
				}
			}
		}
		for (m, n, tiled) in [
			(512, 512, true),
			(520, 511, true),
			(600, 600, true),
			// The same threshold crossed in the two non-square orientations:
			// a band bound written from the wrong side (`Ord::min(m, n)`
			// replaced by `n`) walks columns past the end here and not in
			// the square fixtures.
			(17, 16384, true),
			(16384, 17, true),
			(64, 64, false),
			(65, 65, false),
			(300, 300, false),
			(257, 100, false),
			(100, 257, false),
			(17, 300, false),
			(300, 17, false),
			// the power-of-two column stride of `tensor4all/faer#352`: 256 f64
			// columns are 2048 bytes apart, below the byte threshold and still
			// tiled
			(256, 256, true),
		] {
			for flipped in [false, true] {
				check::<f64>(m, n, flipped, tiled);
				check::<crate::c64>(m, n, flipped, tiled);
			}
		}
	}

	/// The threshold is the measured crossover of `tensor4all/faer#323`: the
	/// `512 x 512` f64 pair is the first cell where the tiles win and `511 x 511`
	/// the last one where they lose, with the boundary at the working set and not
	/// at the side. Below that byte count the strides decide, and the strides are
	/// the ones the copy actually sees: an owned `511 x 511` f64 destination is
	/// padded to 512 columns, so its column stride is a power of two and only the
	/// source's 4088-byte row stride keeps it on the walk.
	#[test]
	fn tile_copy_threshold_is_the_measured_crossover() {
		assert_eq!(TILE_COPY_CACHE_BYTES, 2 * 512 * 512 * 8);
		// a square f64 shape below the byte threshold, with the strides its owned
		// destination and its row-major source have in `Llt::new`
		std::assert!(!tile_copy_pays::<f64>(511, 511, 512, 511));
		// the band a padded destination opens: 505..511 have a 4096-byte column
		// stride, a power of two, and a source row stride that is not -- the walk
		// won all of them by 8-12% on `tensor4all/faer#323`
		std::assert!(!tile_copy_pays::<f64>(505, 505, 512, 505));
		std::assert!(!tile_copy_pays::<f64>(508, 508, 512, 508));
		// and the same band one power of two down, where the destination is
		// padded to 256 columns = 2048 bytes
		std::assert!(!tile_copy_pays::<f64>(250, 250, 256, 250));
		std::assert!(!tile_copy_pays::<f64>(255, 255, 256, 255));
		// both strides a power of two: the tiles, at both sizes
		std::assert!(tile_copy_pays::<f64>(256, 256, 256, 256));
		std::assert!(tile_copy_pays::<f64>(512, 512, 512, 512));
		// the band for the other scalars, from a padded owned destination and a
		// row-major source: c64 rounds its columns to a multiple of 4 rows and c32
		// to a multiple of 8, so c64's 4096-byte band is 253..255 (below the byte
		// count, so the clause separates there) and its 8192-byte one is 509..511,
		// the byte clause's business. f32 rounds to 16 rows: 2048 bytes at 512
		std::assert!(!tile_copy_pays::<crate::c64>(126, 126, 128, 126));
		std::assert!(!tile_copy_pays::<crate::c64>(255, 255, 256, 255));
		std::assert!(tile_copy_pays::<crate::c64>(256, 256, 256, 256));
		std::assert!(!tile_copy_pays::<crate::c32>(255, 255, 256, 255));
		std::assert!(tile_copy_pays::<crate::c32>(256, 256, 256, 256));
		std::assert!(!tile_copy_pays::<f32>(505, 505, 512, 505));
		std::assert!(tile_copy_pays::<f32>(512, 512, 512, 512));
		// the known cost kept on purpose: a ragged 513x513 is above the byte
		// threshold, and #290's table records 3.6% against the tiles there
		// over six cells, five of them slower. Raggedness is not why: 528,
		// 1008 and 1040 (`n % 16 == 0`) lose by the same 6-7% -- #323 is open
		// for the byte boundary, not for the remainder of the tile grid
		std::assert!(tile_copy_pays::<f64>(513, 513, 520, 513));
		std::assert!(!tile_copy_pays::<f64>(1, 262143, 1, 1));
		std::assert!(tile_copy_pays::<f64>(1, 262144, 1, 1));
		std::assert!(tile_copy_pays::<f64>(1, 262145, 1, 1));
		std::assert!(!tile_copy_pays::<f32>(724, 724, 724, 724));
		std::assert!(tile_copy_pays::<f32>(725, 725, 725, 725));
		// below the byte threshold and not a power-of-two stride: 511 f32 columns
		// are 2044 bytes apart
		std::assert!(!tile_copy_pays::<f32>(511, 512, 511, 511));
	}

	/// The power-of-two stride of `tensor4all/faer#352`: the tiles pay on
	/// a) a power-of-two destination column stride at or above 2048 bytes together
	/// with a power-of-two source row stride, whatever the element size, and
	/// b) nothing else below the byte threshold.
	#[test]
	fn tile_copy_pays_on_a_power_of_two_stride_pair() {
		assert_eq!(TILE_COPY_POWER_OF_TWO_STRIDE_BYTES, 2048);
		// 256 x 256 f64: the measured cell -- 2048 bytes of stride on both sides,
		// 1 MiB of working set, tiled
		std::assert!(tile_copy_pays::<f64>(256, 256, 256, 256));
		// the same stride from an f32 matrix is 512 columns, and from a c64 one
		// 128: the clause follows the bytes, not the scalar
		std::assert!(tile_copy_pays::<f32>(256, 256, 512, 256));
		std::assert!(tile_copy_pays::<crate::c64>(128, 128, 128, 128));
		// 2040 bytes and 1024 bytes are not above the floor, 2048-3128 bytes that
		// are not a power of two are not a power of two
		std::assert!(!tile_copy_pays::<f64>(255, 255, 255, 255));
		std::assert!(!tile_copy_pays::<f64>(128, 128, 128, 128));
		std::assert!(!tile_copy_pays::<f64>(260, 260, 260, 260));
		// a destination whose columns are further apart than its rows: the stride
		// is what is judged, not the shape
		std::assert!(tile_copy_pays::<f64>(256, 100, 256, 256));
		// the source side is load-bearing: the same destination stride with a
		// source row stride that is not a power of two takes the walk
		std::assert!(!tile_copy_pays::<f64>(256, 100, 256, 100));
	}

	/// The choice is made on the working set, on the same transposed layout: one
	/// shape below the threshold takes the elementwise walk, one above it takes
	/// the tiles, and `copy_lower_across_layouts` reports which it took. The
	/// predicate is asked with the destination's and the source's real strides,
	/// padding included -- asking it with `m` in place of the padded column stride
	/// is how `505`..`511` came to be tiled on a stride the destination does not
	/// have.
	#[test]
	fn tile_copy_is_chosen_on_the_working_set_not_on_the_layout() {
		fn check<T: Entry>((m, n, want): (usize, usize, bool)) {
			let (_, rm) = fixture::<T>(m, n, false);
			let src = MatRef::from_row_major_slice(&rm, m, n);
			let mut dst = Mat::<T>::zeros(m, n);
			assert_eq!(
				tile_copy_pays::<T>(m, n, dst.col_stride(), src.row_stride()),
				want,
				"{m}x{n}"
			);
			assert_eq!(
				copy_lower_across_layouts(dst.as_mut(), src),
				want,
				"{m}x{n}"
			);
		}
		for shape in [
			// the power-of-two stride pair of #352, on the shape it was measured on
			(256, 256, true),
			// one column apart from it, and no power of two: the walk
			(257, 257, false),
			(512, 512, true),
			// the band a padded destination opens, below the byte count for both
			// scalars: 2048 bytes of column stride for f64 and 4096 for c64, with a
			// source row stride of 2040 and 4080 bytes
			(255, 255, false),
			// both rectangles: the tiled fixtures of the value test cross the
			// threshold in either orientation, and the helper must report the
			// same choice there
			(511, 520, true),
			(1024, 256, true),
		] {
			check::<f64>(shape);
			check::<crate::c64>(shape);
		}
	}

	/// The gate for the tiled copy: `Llt::new` and `PartialPivLu::new` given the
	/// same matrix as a row-major and as a column-major view leave the same
	/// factors, entry for entry and bit for bit, and the same permutation. The
	/// copy is the only step that differs between the two orders, so anything
	/// it got wrong shows here.
	#[test]
	fn llt_and_partial_piv_lu_factor_both_orders_bit_for_bit() {
		use crate::linalg::solvers::{Llt, PartialPivLu};
		fn same<T: Entry>(what: &str, a: MatRef<'_, T>, b: MatRef<'_, T>) {
			for j in 0..a.ncols() {
				for i in 0..a.nrows() {
					if !a[(i, j)].same(&b[(i, j)]) {
						panic!("{what}: entry ({i}, {j}) differs between the two orders");
					}
				}
			}
		}
		for n in [65, 129, 300] {
			let (cm, rm) = fixture::<f64>(n, n, false);
			let cm = MatRef::from_column_major_slice(&cm, n, n);
			let rm = MatRef::from_row_major_slice(&rm, n, n);
			// symmetric positive definite: A Aᵀ + n I, built once and laid out both ways
			let spd = Mat::<f64>::from_fn(n, n, |i, j| {
				let mut s = if i == j { n as f64 } else { 0.0 };
				for k in 0..n {
					s += cm[(i, k)] * cm[(j, k)];
				}
				s
			});
			let spd_cm: Vec<f64> = (0..n * n).map(|k| spd[(k % n, k / n)]).collect();
			let spd_rm: Vec<f64> = (0..n * n).map(|k| spd[(k / n, k % n)]).collect();
			let run = |par: Par<'_>| {
				let a = Llt::new(
					MatRef::from_column_major_slice(&spd_cm, n, n),
					Side::Lower,
					Par::Seq,
				)
				.unwrap();
				let b = Llt::new(
					MatRef::from_row_major_slice(&spd_rm, n, n),
					Side::Lower,
					par,
				)
				.unwrap();
				same(&format!("llt {n}"), a.L(), b.L());
			};
			run(Par::Seq);
			crate::team::with_team(8, |par| run(par));
			let a = PartialPivLu::new(cm, Par::Seq);
			let b = PartialPivLu::new(rm, Par::Seq);
			same(&format!("lu L {n}"), a.L(), b.L());
			same(&format!("lu U {n}"), a.U(), b.U());
			std::assert_eq!(a.P().arrays(), b.P().arrays(), "lu {n}: permutations differ");
		}
	}
}