1use ndarray::{Array1, Array2, Array3, ArrayView1, ArrayView2, ArrayView3};
23
24use super::device_runtime::GpuRuntime;
25use super::policy::GpuDispatchPolicy;
26use super::GpuPolicy;
27
28pub struct CudaGemmDispatch;
29
30impl gam_linalg::gpu_hook::GpuGemmDispatch for CudaGemmDispatch {
31 fn try_fast_atb(&self, a: ArrayView2<'_, f64>, b: ArrayView2<'_, f64>) -> Option<Array2<f64>> {
32 try_fast_atb(a, b)
33 }
34
35 fn try_fast_ab(&self, a: ArrayView2<'_, f64>, b: ArrayView2<'_, f64>) -> Option<Array2<f64>> {
36 try_fast_ab(a, b)
37 }
38
39 fn try_fast_av(&self, a: ArrayView2<'_, f64>, v: ArrayView1<'_, f64>) -> Option<Array1<f64>> {
40 try_fast_av(a, v)
41 }
42
43 fn try_fast_atv(&self, a: ArrayView2<'_, f64>, v: ArrayView1<'_, f64>) -> Option<Array1<f64>> {
44 try_fast_atv(a, v)
45 }
46
47 fn try_fast_xt_diag_x(
48 &self,
49 x: ArrayView2<'_, f64>,
50 w: ArrayView1<'_, f64>,
51 ) -> Option<Array2<f64>> {
52 try_fast_xt_diag_x(x, w)
53 }
54
55 fn try_fast_xt_diag_y(
56 &self,
57 x: ArrayView2<'_, f64>,
58 w: ArrayView1<'_, f64>,
59 y: ArrayView2<'_, f64>,
60 ) -> Option<Array2<f64>> {
61 try_fast_xt_diag_y(x, w, y)
62 }
63
64 fn try_fast_joint_hessian_2x2(
65 &self,
66 x_a: ArrayView2<'_, f64>,
67 x_b: ArrayView2<'_, f64>,
68 w_aa: ArrayView1<'_, f64>,
69 w_ab: ArrayView1<'_, f64>,
70 w_bb: ArrayView1<'_, f64>,
71 ) -> Option<Array2<f64>> {
72 try_fast_joint_hessian_2x2(x_a, x_b, w_aa, w_ab, w_bb)
73 }
74
75 fn device_count(&self) -> usize {
76 let policy = super::global_policy();
77 runtime_for_dispatch(policy).map_or(0, GpuRuntime::device_count)
78 }
79
80 fn try_fast_ab_broadcast_b_batched(
81 &self,
82 a3: ArrayView3<'_, f64>,
83 b: ArrayView2<'_, f64>,
84 ) -> Option<Array3<f64>> {
85 try_fast_ab_broadcast_b_batched(a3, b)
86 }
87}
88
89#[derive(Clone, Copy, Debug)]
92pub enum DispatchOp {
93 Gemm { m: usize, n: usize, k: usize },
95 BatchedGemm {
97 batch: usize,
98 m: usize,
99 n: usize,
100 k: usize,
101 },
102 Potrf { p: usize, batch: usize },
104 SmallDenseBatchedPotrf { p: usize, batch: usize },
109 Trsm { m: usize, n: usize },
111 Gemv { m: usize, k: usize },
113 XtDiagX { n: usize, p: usize },
115 XtDiagY { n: usize, px: usize, q: usize },
117 JointHessian2x2 { n: usize, pa: usize, pb: usize },
119}
120
121#[inline]
126fn runtime_for_dispatch(policy: GpuPolicy) -> Option<&'static GpuRuntime> {
127 GpuRuntime::resolve(policy).unwrap_or_else(|error| {
128 panic!(
132 "GPU runtime resolution failed under policy '{}': {error}",
133 policy
134 )
135 })
136}
137
138#[inline]
143#[track_caller]
144fn decline_gpu<T>(operation: &'static str, reason: &'static str) -> Option<T> {
145 if super::global_policy() == GpuPolicy::Required {
146 panic!("gpu=required operation '{operation}' cannot execute on the GPU: {reason}");
149 }
150 None
151}
152
153#[inline]
157#[track_caller]
158fn invalid_gpu_request(operation: &'static str, reason: &'static str) -> ! {
159 panic!("GPU operation '{operation}' received invalid input: {reason}");
162}
163
164#[cfg(not(target_os = "linux"))]
172#[inline]
173#[track_caller]
174fn decline_gpu_with_policy<T>(
175 operation: &'static str,
176 reason: &'static str,
177 gpu_policy: GpuPolicy,
178) -> Option<T> {
179 if gpu_policy == GpuPolicy::Required {
180 panic!("gpu=required operation '{operation}' cannot execute on the GPU: {reason}");
183 }
184 None
185}
186
187#[cfg(target_os = "linux")]
189#[inline]
190#[track_caller]
191fn invalid_gpu_result(operation: &'static str, reason: &'static str) -> ! {
192 panic!("GPU operation '{operation}' produced invalid output: {reason}");
195}
196
197#[cfg(target_os = "linux")]
202#[inline]
203#[track_caller]
204fn complete_gpu_attempt<T>(operation: &'static str, result: Option<T>) -> T {
205 match result {
206 Some(value) => value,
207 None => panic!(
211 "GPU operation '{operation}' failed after admission under policy '{}'",
212 super::global_policy()
213 ),
214 }
215}
216
217impl DispatchOp {
218 #[inline]
220 pub const fn flops(self) -> u128 {
221 match self {
222 Self::Gemm { m, n, k } => 2u128 * (m as u128) * (n as u128) * (k as u128),
223 Self::BatchedGemm { batch, m, n, k } => {
224 2u128 * (batch as u128) * (m as u128) * (n as u128) * (k as u128)
225 }
226 Self::Gemv { m, k } => 2u128 * (m as u128) * (k as u128),
227 Self::Potrf { p, batch } => (batch as u128) * (p as u128).pow(3) / 3,
228 Self::SmallDenseBatchedPotrf { p, batch } => (batch as u128) * (p as u128).pow(3) / 3,
229 Self::Trsm { m, n } => (m as u128) * (m as u128) * (n as u128),
230 Self::XtDiagX { n, p } => 2u128 * (n as u128) * (p as u128) * (p as u128),
231 Self::XtDiagY { n, px, q } => 2u128 * (n as u128) * (px as u128) * (q as u128),
232 Self::JointHessian2x2 { n, pa, pb } => {
233 let total = (pa as u128) + (pb as u128);
234 2u128 * (n as u128) * total * total
235 }
236 }
237 }
238
239 #[must_use]
254 pub fn admissible_under_any_policy(self) -> bool {
255 let seed = GpuDispatchPolicy::default();
256 let min_gemm = GpuDispatchPolicy::MIN_CALIBRATABLE_GEMM_FLOPS;
257 match self {
258 Self::Gemm { m, n, k } => self.flops() >= min_gemm && m.min(n).min(k) > 0,
259 Self::BatchedGemm { batch, m, n, k } => {
260 self.flops() >= min_gemm && batch > 1 && m.min(n).min(k) > 0
261 }
262 Self::Gemv { m, k } => self.flops() >= min_gemm && m > 0 && k > 0,
263 Self::Potrf { p, batch } => {
264 p > 0
265 && batch > 0
266 && (p >= GpuDispatchPolicy::MIN_CALIBRATABLE_POTRF_P
267 || (batch > 1 && self.flops() >= min_gemm))
268 }
269 Self::SmallDenseBatchedPotrf { p, batch } => {
272 p > 0
273 && p <= seed.small_dense_batched_potrf_max_p
274 && batch >= seed.small_dense_batched_potrf_min_batch
275 }
276 Self::Trsm { m, n } => self.flops() >= min_gemm && m > 0 && n > 0,
277 Self::XtDiagX { n, p } => n > 0 && p > 0 && self.flops() >= min_gemm,
282 Self::XtDiagY { n, px, q } => n > 0 && px > 0 && q > 0 && self.flops() >= min_gemm,
283 Self::JointHessian2x2 { n, pa, pb } => {
284 n > 0 && (pa > 0 || pb > 0) && self.flops() >= min_gemm
285 }
286 }
287 }
288}
289
290#[inline]
295#[must_use]
296pub fn route_through_gpu(op: DispatchOp) -> Option<&'static GpuRuntime> {
297 route_through_gpu_with_policy(op, super::global_policy())
298}
299
300#[inline]
304#[must_use]
305pub fn route_through_gpu_with_policy(
306 op: DispatchOp,
307 selected_policy: GpuPolicy,
308) -> Option<&'static GpuRuntime> {
309 if selected_policy != GpuPolicy::Required && !op.admissible_under_any_policy() {
316 return None;
317 }
318 let runtime = runtime_for_dispatch(selected_policy)?;
319 if selected_policy == GpuPolicy::Required {
320 return Some(runtime);
321 }
322 let policy = &runtime.policy;
323 let admit = match op {
324 DispatchOp::Gemm { m, n, k } => {
325 op.flops() >= (policy.gemm_min_flops as u128) && m.min(n).min(k) > 0
326 }
327 DispatchOp::BatchedGemm { batch, m, n, k } => {
328 op.flops() >= (policy.gemm_min_flops as u128) && batch > 1 && m.min(n).min(k) > 0
329 }
330 DispatchOp::Gemv { m, k } => {
331 op.flops() >= (policy.gemm_min_flops as u128) && m > 0 && k > 0
332 }
333 DispatchOp::Potrf { p, batch } => {
334 p > 0
335 && batch > 0
336 && (p >= policy.potrf_min_p
337 || (batch > 1 && op.flops() >= policy.gemm_min_flops as u128))
338 }
339 DispatchOp::SmallDenseBatchedPotrf { p, batch } => {
340 p > 0
341 && p <= policy.small_dense_batched_potrf_max_p
342 && batch >= policy.small_dense_batched_potrf_min_batch
343 }
344 DispatchOp::Trsm { m, n } => {
345 op.flops() >= (policy.gemm_min_flops as u128) && m > 0 && n > 0
346 }
347 DispatchOp::XtDiagX { n, p } => policy.xtwx_target_is_gpu(n, p, true),
348 DispatchOp::XtDiagY { n, px, q } => policy.xtwy_target_is_gpu(n, px, q, true),
349 DispatchOp::JointHessian2x2 { n, pa, pb } => {
350 n > 0 && (pa > 0 || pb > 0) && op.flops() >= policy.gemm_min_flops as u128
351 }
352 };
353 if admit { Some(runtime) } else { None }
354}
355
356#[cfg(target_os = "linux")]
363const MULTI_GPU_BATCH_FLOOR: usize = 64;
364
365#[cfg(target_os = "linux")]
368#[inline]
369fn should_split_batch(batch: usize) -> bool {
370 let policy = super::global_policy();
371 runtime_for_dispatch(policy).is_some_and(|rt| rt.device_count() > 1)
372 && batch >= MULTI_GPU_BATCH_FLOOR
373}
374
375#[inline]
376#[must_use]
377pub fn try_fast_ab_broadcast_b_batched(
378 a: ArrayView3<'_, f64>,
379 b: ArrayView2<'_, f64>,
380) -> Option<Array3<f64>> {
381 let (batch, m, k) = a.dim();
382 let (bk, n) = b.dim();
383 if k != bk {
384 invalid_gpu_request("batched A·B", "the reduction dimensions differ");
385 }
386 if batch == 0 || m == 0 || n == 0 || k == 0 {
387 return decline_gpu(
388 "batched A·B",
389 "the workload has an empty dimension",
390 );
391 }
392 #[cfg(not(target_os = "linux"))]
393 {
394 return decline_gpu("batched A·B", "the CUDA backend is not compiled on this platform");
395 }
396 #[cfg(target_os = "linux")]
397 {
398 let runtime = route_through_gpu(DispatchOp::BatchedGemm { batch, m, n, k })?;
399 if should_split_batch(batch) {
400 if let Some(out) = scatter_broadcast_b_batched(runtime, a, b, m, n) {
401 return Some(out);
402 }
403 }
406 Some(complete_gpu_attempt(
407 "batched A·B",
408 cuda_backend::gemm_broadcast_b_batched(runtime.device.ordinal, a, b),
409 ))
410 }
411}
412
413#[cfg(target_os = "linux")]
419fn scatter_broadcast_b_batched(
420 runtime: &GpuRuntime,
421 a: ArrayView3<'_, f64>,
422 b: ArrayView2<'_, f64>,
423 m: usize,
424 n: usize,
425) -> Option<Array3<f64>> {
426 let batch = a.dim().0;
427 let mut items: Vec<(Array2<f64>, Option<Array2<f64>>)> = (0..batch)
430 .map(|i| (a.index_axis(ndarray::Axis(0), i).to_owned(), None))
431 .collect();
432 super::pool::scatter_batched(runtime, &mut items, |ordinal, tile| {
433 let tile_batch = tile.len();
434 if tile_batch == 0 {
435 return Some(());
436 }
437 let k = b.dim().0;
438 let mut a_tile = Array3::<f64>::zeros((tile_batch, m, k));
439 for (idx, (a_i, _)) in tile.iter().enumerate() {
440 a_tile.index_axis_mut(ndarray::Axis(0), idx).assign(a_i);
441 }
442 let out = cuda_backend::gemm_broadcast_b_batched(ordinal, a_tile.view(), b)?;
443 for (idx, (_, slot)) in tile.iter_mut().enumerate() {
444 *slot = Some(out.index_axis(ndarray::Axis(0), idx).to_owned());
445 }
446 Some(())
447 })?;
448 stitch_batched(items, m, n)
449}
450
451#[inline]
452#[must_use]
453pub fn try_fast_abt_strided_batched(
454 a: ArrayView3<'_, f64>,
455 b: ArrayView3<'_, f64>,
456) -> Option<Array3<f64>> {
457 try_fast_abt_strided_batched_with_policy(a, b, super::global_policy())
458}
459
460#[inline]
461#[must_use]
462pub fn try_fast_abt_strided_batched_with_policy(
463 a: ArrayView3<'_, f64>,
464 b: ArrayView3<'_, f64>,
465 gpu_policy: GpuPolicy,
466) -> Option<Array3<f64>> {
467 let (batch, m, k) = a.dim();
468 let (batch_b, n, k_b) = b.dim();
469 if batch != batch_b || k != k_b {
470 invalid_gpu_request("batched A·Bᵀ", "the batch or reduction dimensions differ");
471 }
472 if batch == 0 || m == 0 || n == 0 || k == 0 {
473 return decline_gpu(
474 "batched A·Bᵀ",
475 "the workload has an empty dimension",
476 );
477 }
478 #[cfg(not(target_os = "linux"))]
479 {
480 return decline_gpu_with_policy(
481 "batched A·Bᵀ",
482 "the CUDA backend is not compiled on this platform",
483 gpu_policy,
484 );
485 }
486 #[cfg(target_os = "linux")]
487 {
488 let runtime =
489 route_through_gpu_with_policy(DispatchOp::BatchedGemm { batch, m, n, k }, gpu_policy)?;
490 if should_split_batch(batch) {
491 if let Some(out) = scatter_abt_strided_batched(runtime, a, b, m, n) {
492 return Some(out);
493 }
494 }
495 Some(complete_gpu_attempt(
496 "batched A·Bᵀ",
497 cuda_backend::gemm_abt_strided_batched(runtime.device.ordinal, a, b),
498 ))
499 }
500}
501
502#[cfg(target_os = "linux")]
507fn scatter_abt_strided_batched(
508 runtime: &GpuRuntime,
509 a: ArrayView3<'_, f64>,
510 b: ArrayView3<'_, f64>,
511 m: usize,
512 n: usize,
513) -> Option<Array3<f64>> {
514 let batch = a.dim().0;
515 let mut items: Vec<(Array2<f64>, Array2<f64>, Option<Array2<f64>>)> = (0..batch)
516 .map(|i| {
517 (
518 a.index_axis(ndarray::Axis(0), i).to_owned(),
519 b.index_axis(ndarray::Axis(0), i).to_owned(),
520 None,
521 )
522 })
523 .collect();
524 super::pool::scatter_batched(runtime, &mut items, |ordinal, tile| {
525 let tile_batch = tile.len();
526 if tile_batch == 0 {
527 return Some(());
528 }
529 let k = tile[0].0.dim().1;
530 let mut a_tile = Array3::<f64>::zeros((tile_batch, m, k));
531 let mut b_tile = Array3::<f64>::zeros((tile_batch, n, k));
532 for (idx, (a_i, b_i, _)) in tile.iter().enumerate() {
533 a_tile.index_axis_mut(ndarray::Axis(0), idx).assign(a_i);
534 b_tile.index_axis_mut(ndarray::Axis(0), idx).assign(b_i);
535 }
536 let out = cuda_backend::gemm_abt_strided_batched(ordinal, a_tile.view(), b_tile.view())?;
537 for (idx, (_, _, slot)) in tile.iter_mut().enumerate() {
538 *slot = Some(out.index_axis(ndarray::Axis(0), idx).to_owned());
539 }
540 Some(())
541 })?;
542 let slots: Vec<((), Option<Array2<f64>>)> =
543 items.into_iter().map(|(_, _, slot)| ((), slot)).collect();
544 stitch_batched(slots, m, n)
545}
546
547#[cfg(target_os = "linux")]
551fn stitch_batched<L>(
552 items: Vec<(L, Option<Array2<f64>>)>,
553 m: usize,
554 n: usize,
555) -> Option<Array3<f64>> {
556 let batch = items.len();
557 let mut out = Array3::<f64>::zeros((batch, m, n));
558 for (idx, (_, slot)) in items.into_iter().enumerate() {
559 let block = slot?;
560 if block.dim() != (m, n) {
561 return None;
562 }
563 out.index_axis_mut(ndarray::Axis(0), idx).assign(&block);
564 }
565 Some(out)
566}
567
568#[inline]
582#[must_use]
583pub fn try_fast_ab(a: ArrayView2<'_, f64>, b: ArrayView2<'_, f64>) -> Option<Array2<f64>> {
584 let (m, k) = a.dim();
585 let (kb, n) = b.dim();
586 if k != kb {
587 invalid_gpu_request("A·B", "the reduction dimensions differ");
588 }
589 if m == 0 || n == 0 || k == 0 {
590 return decline_gpu("A·B", "the workload has an empty dimension");
591 }
592 let runtime = route_through_gpu(DispatchOp::Gemm { m, n, k });
598 let used_gpu = runtime.is_some();
599 super::profile::record(super::profile::KernelStat {
600 name: "try_fast_ab",
601 n: m,
602 p: n,
603 k,
604 flops_est: (DispatchOp::Gemm { m, n, k }.flops().min(usize::MAX as u128)) as usize,
605 gpu_ms: if used_gpu { Some(0.0) } else { None },
606 ..Default::default()
607 });
608 #[cfg(not(target_os = "linux"))]
609 {
610 decline_gpu("A·B", "the CUDA backend is not compiled on this platform")
611 }
612 #[cfg(target_os = "linux")]
613 {
614 let runtime = runtime?;
615 Some(complete_gpu_attempt(
616 "A·B",
617 cuda_backend::gemm(runtime, a, b, false, false),
618 ))
619 }
620}
621
622#[inline]
623#[must_use]
624pub fn try_fast_atb(a: ArrayView2<'_, f64>, b: ArrayView2<'_, f64>) -> Option<Array2<f64>> {
625 let (n_a, p) = a.dim();
626 let (n_b, q) = b.dim();
627 if n_a != n_b {
628 invalid_gpu_request("Aᵀ·B", "the row dimensions differ");
629 }
630 if n_a == 0 || p == 0 || q == 0 {
631 return decline_gpu("Aᵀ·B", "the workload has an empty dimension");
632 }
633 #[cfg(not(target_os = "linux"))]
634 {
635 return decline_gpu("Aᵀ·B", "the CUDA backend is not compiled on this platform");
636 }
637 #[cfg(target_os = "linux")]
638 {
639 let runtime = route_through_gpu(DispatchOp::Gemm { m: p, n: q, k: n_a })?;
640 Some(complete_gpu_attempt(
641 "Aᵀ·B",
642 cuda_backend::gemm(runtime, a, b, true, false),
643 ))
644 }
645}
646
647#[inline]
656#[must_use]
657pub fn try_fast_atb_on_ordinal(
658 ordinal: usize,
659 a: ArrayView2<'_, f64>,
660 b: ArrayView2<'_, f64>,
661) -> Option<Array2<f64>> {
662 let (n_a, p) = a.dim();
663 let (n_b, q) = b.dim();
664 if n_a != n_b {
665 invalid_gpu_request("ordinal-pinned Aᵀ·B", "the row dimensions differ");
666 }
667 if n_a == 0 || p == 0 || q == 0 {
668 return decline_gpu(
669 "ordinal-pinned Aᵀ·B",
670 "the workload has an empty dimension",
671 );
672 }
673 #[cfg(not(target_os = "linux"))]
674 {
675 log::trace!(
681 "try_fast_atb_on_ordinal: CUDA unavailable off Linux; declining ordinal {ordinal}"
682 );
683 return decline_gpu(
684 "ordinal-pinned Aᵀ·B",
685 "the CUDA backend is not compiled on this platform",
686 );
687 }
688 #[cfg(target_os = "linux")]
689 {
690 route_through_gpu(DispatchOp::Gemm { m: p, n: q, k: n_a })?;
702 Some(complete_gpu_attempt(
703 "ordinal-pinned Aᵀ·B",
704 cuda_backend::gemm_on_ordinal(ordinal, a, b, true, false),
705 ))
706 }
707}
708
709#[inline]
710#[must_use]
711pub fn try_fast_av(a: ArrayView2<'_, f64>, v: ArrayView1<'_, f64>) -> Option<Array1<f64>> {
712 let (m, k) = a.dim();
713 if k != v.len() {
714 invalid_gpu_request("A·v", "the matrix width and vector length differ");
715 }
716 if m == 0 || k == 0 {
717 return decline_gpu("A·v", "the workload has an empty dimension");
718 }
719 #[cfg(not(target_os = "linux"))]
720 {
721 return decline_gpu("A·v", "the CUDA backend is not compiled on this platform");
722 }
723 #[cfg(target_os = "linux")]
724 {
725 let runtime = route_through_gpu(DispatchOp::Gemv { m, k })?;
726 Some(complete_gpu_attempt(
727 "A·v",
728 cuda_backend::gemv(runtime, a, v, false),
729 ))
730 }
731}
732
733#[inline]
734#[must_use]
735pub fn try_fast_atv(a: ArrayView2<'_, f64>, v: ArrayView1<'_, f64>) -> Option<Array1<f64>> {
736 let (n, p) = a.dim();
737 if n != v.len() {
738 invalid_gpu_request("Aᵀ·v", "the matrix height and vector length differ");
739 }
740 if n == 0 || p == 0 {
741 return decline_gpu("Aᵀ·v", "the workload has an empty dimension");
742 }
743 #[cfg(not(target_os = "linux"))]
744 {
745 return decline_gpu("Aᵀ·v", "the CUDA backend is not compiled on this platform");
746 }
747 #[cfg(target_os = "linux")]
748 {
749 let runtime = route_through_gpu(DispatchOp::Gemv { m: p, k: n })?;
750 Some(complete_gpu_attempt(
751 "Aᵀ·v",
752 cuda_backend::gemv(runtime, a, v, true),
753 ))
754 }
755}
756
757#[inline]
758#[must_use]
759pub fn try_fast_xt_diag_x(x: ArrayView2<'_, f64>, w: ArrayView1<'_, f64>) -> Option<Array2<f64>> {
760 let (n, p) = x.dim();
761 if n != w.len() {
762 invalid_gpu_request("Xᵀ·diag(w)·X", "the row and weight counts differ");
763 }
764 if n == 0 || p == 0 {
765 return decline_gpu("Xᵀ·diag(w)·X", "the workload has an empty dimension");
766 }
767 #[cfg(not(target_os = "linux"))]
768 {
769 return decline_gpu(
770 "Xᵀ·diag(w)·X",
771 "the CUDA backend is not compiled on this platform",
772 );
773 }
774 #[cfg(target_os = "linux")]
775 {
776 let runtime = route_through_gpu(DispatchOp::XtDiagX { n, p })?;
777 Some(complete_gpu_attempt(
778 "Xᵀ·diag(w)·X",
779 cuda_backend::xt_diag_x(runtime, x, w),
780 ))
781 }
782}
783
784pub struct ResidentDesignGram {
805 #[cfg(target_os = "linux")]
806 inner: super::blas::ResidentWeightedGram,
807 #[cfg(not(target_os = "linux"))]
808 _never: std::convert::Infallible,
809}
810
811impl ResidentDesignGram {
812 #[must_use]
816 pub fn try_new(x: ArrayView2<'_, f64>) -> Option<Self> {
817 let (n, p) = x.dim();
818 if n == 0 || p == 0 {
819 return decline_gpu("resident weighted Gram upload", "the design matrix is empty");
820 }
821 #[cfg(not(target_os = "linux"))]
822 {
823 decline_gpu(
824 "resident weighted Gram upload",
825 "the CUDA backend is not compiled on this platform",
826 )
827 }
828 #[cfg(target_os = "linux")]
829 {
830 let runtime = route_through_gpu(DispatchOp::XtDiagX { n, p })?;
831 let inner = complete_gpu_attempt(
832 "resident weighted Gram upload",
833 super::blas::ResidentWeightedGram::new(runtime.device.ordinal, x),
834 );
835 Some(Self { inner })
836 }
837 }
838
839 #[must_use]
843 pub fn gram(&self, w: ArrayView1<'_, f64>) -> Option<Array2<f64>> {
844 #[cfg(not(target_os = "linux"))]
845 {
846 panic!(
852 "ResidentDesignGram cannot be constructed off CUDA (w.len()={})",
853 w.len()
854 )
855 }
856 #[cfg(target_os = "linux")]
857 {
858 Some(complete_gpu_attempt(
859 "resident Xᵀ·diag(w)·X",
860 self.inner.gram(w),
861 ))
862 }
863 }
864
865 #[must_use]
878 pub fn solve_normal_equations(
879 &self,
880 w: ArrayView1<'_, f64>,
881 rhs: ArrayView1<'_, f64>,
882 ridge: f64,
883 ) -> Option<Array1<f64>> {
884 #[cfg(not(target_os = "linux"))]
885 {
886 panic!(
888 "ResidentDesignGram cannot be constructed off CUDA (w.len()={}, rhs.len()={}, ridge={ridge})",
889 w.len(),
890 rhs.len()
891 )
892 }
893 #[cfg(target_os = "linux")]
894 {
895 Some(complete_gpu_attempt(
896 "resident normal-equations solve",
897 self.inner.solve_psd_normal_equations(w, rhs, ridge),
898 ))
899 }
900 }
901
902 #[must_use]
904 pub fn dims(&self) -> (usize, usize) {
905 #[cfg(not(target_os = "linux"))]
906 {
907 panic!("ResidentDesignGram cannot be constructed off CUDA")
911 }
912 #[cfg(target_os = "linux")]
913 {
914 self.inner.dims()
915 }
916 }
917}
918
919#[cfg(target_os = "linux")]
925const LEVERAGE_CHUNKS_PER_DEVICE: usize = 4;
926
927#[cfg(target_os = "linux")]
932#[inline]
933fn leverage_chunk_rows(cols: usize, n_rows: usize) -> usize {
934 const TARGET_BYTES: usize = 8 * 1024 * 1024;
935 const MIN_CHUNK_ROWS: usize = 512;
936 let bytes_per_row = cols.max(1) * std::mem::size_of::<f64>();
937 (TARGET_BYTES / bytes_per_row)
938 .max(MIN_CHUNK_ROWS)
939 .min(n_rows.max(1))
940}
941
942#[inline]
959#[must_use]
960pub fn try_fast_spectral_leverage_diagonal(
961 x: &gam_linalg::matrix::DesignMatrix,
962 g: ArrayView2<'_, f64>,
963) -> Option<Array1<f64>> {
964 let n = x.nrows();
965 let p = x.ncols();
966 let rank = g.ncols();
967 if g.nrows() != p {
968 invalid_gpu_request(
969 "spectral leverage diagonal",
970 "the design width and spectral-factor height differ",
971 );
972 }
973 if n == 0 || p == 0 || rank == 0 {
974 return decline_gpu(
975 "spectral leverage diagonal",
976 "the workload has an empty dimension",
977 );
978 }
979 #[cfg(not(target_os = "linux"))]
980 {
981 return decline_gpu(
982 "spectral leverage diagonal",
983 "the CUDA backend is not compiled on this platform",
984 );
985 }
986 #[cfg(target_os = "linux")]
987 {
988 let runtime = route_through_gpu(DispatchOp::XtDiagX { n, p })?;
991 let device_count = runtime.device_count().max(1);
992 let byte_chunk = leverage_chunk_rows(p + rank, n);
993 let target_chunks = device_count
994 .saturating_mul(LEVERAGE_CHUNKS_PER_DEVICE)
995 .max(1);
996 let chunk_rows = byte_chunk.min(n.div_ceil(target_chunks).max(1)).max(1);
997
998 let mut tiles: Vec<(std::ops::Range<usize>, Option<Array1<f64>>)> = Vec::new();
1001 let mut start = 0usize;
1002 while start < n {
1003 let end = (start + chunk_rows).min(n);
1004 tiles.push((start..end, None));
1005 start = end;
1006 }
1007
1008 complete_gpu_attempt(
1009 "spectral leverage diagonal scatter",
1010 super::pool::scatter_batched(runtime, &mut tiles, |ordinal, tile| {
1011 for (range, slot) in tile.iter_mut() {
1012 let rows = x.try_row_chunk(range.clone()).ok()?;
1013 let xg =
1014 cuda_backend::gemm_on_ordinal(ordinal, rows.view(), g, false, false)?;
1015 let mut out = Array1::<f64>::zeros(range.end - range.start);
1016 for (local, row) in xg.outer_iter().enumerate() {
1017 out[local] = row.iter().map(|&v| v * v).sum();
1018 }
1019 *slot = Some(out);
1020 }
1021 Some(())
1022 }),
1023 );
1024
1025 let mut h = Array1::<f64>::zeros(n);
1026 for (range, slot) in tiles {
1027 let vals = complete_gpu_attempt("spectral leverage diagonal stitch", slot);
1028 if vals.len() != range.end - range.start {
1029 invalid_gpu_result(
1030 "spectral leverage diagonal stitch",
1031 "a device tile produced an invalid row count",
1032 );
1033 }
1034 h.slice_mut(ndarray::s![range]).assign(&vals);
1035 }
1036 Some(h)
1037 }
1038}
1039
1040#[inline]
1041#[must_use]
1042pub fn try_fast_xt_diag_y(
1043 x: ArrayView2<'_, f64>,
1044 w: ArrayView1<'_, f64>,
1045 y: ArrayView2<'_, f64>,
1046) -> Option<Array2<f64>> {
1047 let (n, px) = x.dim();
1048 let (n_y, q) = y.dim();
1049 if n != n_y || n != w.len() {
1050 invalid_gpu_request("Xᵀ·diag(w)·Y", "the row or weight counts differ");
1051 }
1052 if n == 0 || px == 0 || q == 0 {
1053 return decline_gpu(
1054 "Xᵀ·diag(w)·Y",
1055 "the workload has an empty dimension",
1056 );
1057 }
1058 #[cfg(not(target_os = "linux"))]
1059 {
1060 return decline_gpu(
1061 "Xᵀ·diag(w)·Y",
1062 "the CUDA backend is not compiled on this platform",
1063 );
1064 }
1065 #[cfg(target_os = "linux")]
1066 {
1067 let runtime = route_through_gpu(DispatchOp::XtDiagY { n, px, q })?;
1068 Some(complete_gpu_attempt(
1069 "Xᵀ·diag(w)·Y",
1070 cuda_backend::xt_diag_y(runtime, x, w, y),
1071 ))
1072 }
1073}
1074
1075#[inline]
1076#[must_use]
1077pub fn try_fast_joint_hessian_2x2(
1078 x_a: ArrayView2<'_, f64>,
1079 x_b: ArrayView2<'_, f64>,
1080 w_aa: ArrayView1<'_, f64>,
1081 w_ab: ArrayView1<'_, f64>,
1082 w_bb: ArrayView1<'_, f64>,
1083) -> Option<Array2<f64>> {
1084 let (n, pa) = x_a.dim();
1085 let (n_b, pb) = x_b.dim();
1086 if n != n_b || n != w_aa.len() || n != w_ab.len() || n != w_bb.len() {
1087 invalid_gpu_request("joint 2×2 Hessian", "the row or weight counts differ");
1088 }
1089 if n == 0 || (pa == 0 && pb == 0) {
1090 return decline_gpu(
1091 "joint 2×2 Hessian",
1092 "the workload has an empty dimension",
1093 );
1094 }
1095 #[cfg(not(target_os = "linux"))]
1096 {
1097 return decline_gpu(
1098 "joint 2×2 Hessian",
1099 "the CUDA backend is not compiled on this platform",
1100 );
1101 }
1102 #[cfg(target_os = "linux")]
1103 {
1104 let runtime = route_through_gpu(DispatchOp::JointHessian2x2 { n, pa, pb })?;
1105 Some(complete_gpu_attempt(
1106 "joint 2×2 Hessian",
1107 cuda_backend::joint_hessian_2x2(runtime, x_a, x_b, w_aa, w_ab, w_bb),
1108 ))
1109 }
1110}
1111
1112#[inline]
1113#[must_use]
1114pub fn try_cholesky_lower_inplace(a: &mut Array2<f64>) -> Option<()> {
1115 let p = a.nrows();
1116 if p != a.ncols() {
1117 invalid_gpu_request("Cholesky factorization", "the input matrix is non-square");
1118 }
1119 if p == 0 {
1120 return decline_gpu("Cholesky factorization", "the workload has an empty dimension");
1121 }
1122 #[cfg(not(target_os = "linux"))]
1123 {
1124 return decline_gpu(
1125 "Cholesky factorization",
1126 "the CUDA backend is not compiled on this platform",
1127 );
1128 }
1129 #[cfg(target_os = "linux")]
1130 {
1131 let runtime = route_through_gpu(DispatchOp::Potrf { p, batch: 1 })?;
1132 let lower = complete_gpu_attempt(
1133 "Cholesky factorization",
1134 cuda_backend::cholesky_lower(runtime, a.view()),
1135 );
1136 *a = lower;
1137 Some(())
1138 }
1139}
1140
1141#[inline]
1142#[must_use]
1143pub fn try_cholesky_batched_lower_inplace(matrices: &mut [Array2<f64>]) -> Option<()> {
1144 try_cholesky_batched_lower_inplace_with_policy(matrices, super::global_policy())
1145}
1146
1147#[inline]
1148#[must_use]
1149pub fn try_cholesky_batched_lower_inplace_with_policy(
1150 matrices: &mut [Array2<f64>],
1151 gpu_policy: GpuPolicy,
1152) -> Option<()> {
1153 let first = match matrices.first() {
1154 Some(first) => first,
1155 None => return decline_gpu("batched Cholesky factorization", "the batch is empty"),
1156 };
1157 let p = first.nrows();
1158 if first.ncols() != p || matrices.iter().any(|matrix| matrix.dim() != (p, p)) {
1159 invalid_gpu_request(
1160 "batched Cholesky factorization",
1161 "an input matrix is non-square or has a different shape",
1162 );
1163 }
1164 if p == 0 {
1165 return decline_gpu(
1166 "batched Cholesky factorization",
1167 "the workload has an empty dimension",
1168 );
1169 }
1170 #[cfg(not(target_os = "linux"))]
1171 {
1172 return decline_gpu_with_policy(
1173 "batched Cholesky factorization",
1174 "the CUDA backend is not compiled on this platform",
1175 gpu_policy,
1176 );
1177 }
1178 #[cfg(target_os = "linux")]
1179 {
1180 let batch = matrices.len();
1181 let runtime = route_through_gpu_with_policy(
1182 DispatchOp::SmallDenseBatchedPotrf { p, batch },
1183 gpu_policy,
1184 )
1185 .or_else(|| route_through_gpu_with_policy(DispatchOp::Potrf { p, batch }, gpu_policy))?;
1186 if should_split_batch(batch) {
1187 let split = super::pool::scatter_batched(runtime, matrices, |ordinal, tile| {
1193 cuda_backend::cholesky_batched_lower(ordinal, tile)
1194 });
1195 if split.is_some() {
1196 return Some(());
1197 }
1198 }
1199 Some(complete_gpu_attempt(
1200 "batched Cholesky factorization",
1201 cuda_backend::cholesky_batched_lower(runtime.device.ordinal, matrices),
1202 ))
1203 }
1204}
1205
1206#[inline]
1207#[must_use]
1208pub fn try_solve_lower_triangular_matrix(
1209 lower: ArrayView2<'_, f64>,
1210 rhs: ArrayView2<'_, f64>,
1211) -> Option<Array2<f64>> {
1212 let (m, n) = rhs.dim();
1213 if lower.dim() != (m, m) {
1214 invalid_gpu_request(
1215 "lower-triangular solve",
1216 "the triangular matrix shape does not match the right-hand side",
1217 );
1218 }
1219 if m == 0 || n == 0 {
1220 return decline_gpu(
1221 "lower-triangular solve",
1222 "the workload has an empty dimension",
1223 );
1224 }
1225 #[cfg(not(target_os = "linux"))]
1226 {
1227 return decline_gpu(
1228 "lower-triangular solve",
1229 "the CUDA backend is not compiled on this platform",
1230 );
1231 }
1232 #[cfg(target_os = "linux")]
1233 {
1234 let runtime = route_through_gpu(DispatchOp::Trsm { m, n })?;
1235 Some(complete_gpu_attempt(
1236 "lower-triangular solve",
1237 cuda_backend::trsm(runtime, lower, rhs, false),
1238 ))
1239 }
1240}
1241
1242#[inline]
1243#[must_use]
1244pub fn try_solve_upper_triangular_matrix(
1245 upper: ArrayView2<'_, f64>,
1246 rhs: ArrayView2<'_, f64>,
1247) -> Option<Array2<f64>> {
1248 let (m, n) = rhs.dim();
1249 if upper.dim() != (m, m) {
1250 invalid_gpu_request(
1251 "upper-triangular solve",
1252 "the triangular matrix shape does not match the right-hand side",
1253 );
1254 }
1255 if m == 0 || n == 0 {
1256 return decline_gpu(
1257 "upper-triangular solve",
1258 "the workload has an empty dimension",
1259 );
1260 }
1261 #[cfg(not(target_os = "linux"))]
1262 {
1263 return decline_gpu(
1264 "upper-triangular solve",
1265 "the CUDA backend is not compiled on this platform",
1266 );
1267 }
1268 #[cfg(target_os = "linux")]
1269 {
1270 let runtime = route_through_gpu(DispatchOp::Trsm { m, n })?;
1271 Some(complete_gpu_attempt(
1272 "upper-triangular solve",
1273 cuda_backend::trsm(runtime, upper, rhs, true),
1274 ))
1275 }
1276}
1277
1278#[cfg(test)]
1279mod pre_probe_gate_tests {
1280 use super::{DispatchOp, GpuDispatchPolicy, route_through_gpu};
1287 use crate::device_runtime::GpuRuntime;
1288
1289 #[test]
1290 fn cpu_sized_ops_are_refused_before_the_device_probe() {
1291 let tiny_ops = [
1292 DispatchOp::Gemm { m: 8, n: 8, k: 8 },
1293 DispatchOp::BatchedGemm {
1294 batch: 4,
1295 m: 8,
1296 n: 8,
1297 k: 8,
1298 },
1299 DispatchOp::Gemv { m: 64, k: 64 },
1300 DispatchOp::Potrf { p: 24, batch: 1 },
1301 DispatchOp::Trsm { m: 16, n: 16 },
1302 DispatchOp::XtDiagX { n: 700, p: 12 },
1303 DispatchOp::XtDiagY {
1304 n: 700,
1305 px: 12,
1306 q: 4,
1307 },
1308 DispatchOp::JointHessian2x2 {
1309 n: 700,
1310 pa: 8,
1311 pb: 8,
1312 },
1313 ];
1314 let before = GpuRuntime::resolution_call_count();
1315 for op in tiny_ops {
1316 assert!(
1317 !op.admissible_under_any_policy(),
1318 "fixture op must be inadmissible under every policy: {op:?}"
1319 );
1320 assert!(
1321 route_through_gpu(op).is_none(),
1322 "inadmissible op must not route: {op:?}"
1323 );
1324 }
1325 assert_eq!(
1326 GpuRuntime::resolution_call_count(),
1327 before,
1328 "route_through_gpu must refuse CPU-sized ops BEFORE runtime resolution, \
1329 so no CUDA context is ever created for them"
1330 );
1331 }
1332
1333 #[test]
1334 fn admissible_ops_fall_through_to_the_probed_runtime() {
1335 let big = DispatchOp::Gemm {
1338 m: 2_048,
1339 n: 2_048,
1340 k: 2_048,
1341 };
1342 assert!(big.admissible_under_any_policy());
1343 let before = GpuRuntime::resolution_call_count();
1344 let routed = route_through_gpu(big);
1345 assert!(
1346 routed.is_none_or(|runtime| !runtime.devices.is_empty()),
1347 "a routed operation must receive a runtime with at least one usable device"
1348 );
1349 assert!(
1350 GpuRuntime::resolution_call_count() > before,
1351 "an admissible op must fall through to runtime resolution"
1352 );
1353 }
1354
1355 #[test]
1356 fn admissibility_bound_never_tightens_the_real_admission() {
1357 let floor_policy = GpuDispatchPolicy {
1363 gemm_min_flops: usize::try_from(GpuDispatchPolicy::MIN_CALIBRATABLE_GEMM_FLOPS)
1364 .expect("fits usize"),
1365 potrf_min_p: GpuDispatchPolicy::MIN_CALIBRATABLE_POTRF_P,
1366 xtwx_flops_min: 4_194_304, ..GpuDispatchPolicy::default()
1368 };
1369 let policies = [GpuDispatchPolicy::default(), floor_policy];
1370 let ops = [
1371 DispatchOp::Gemm {
1372 m: 64,
1373 n: 64,
1374 k: 64,
1375 },
1376 DispatchOp::Gemm {
1377 m: 63,
1378 n: 64,
1379 k: 64,
1380 },
1381 DispatchOp::BatchedGemm {
1382 batch: 8,
1383 m: 64,
1384 n: 64,
1385 k: 8,
1386 },
1387 DispatchOp::Gemv { m: 512, k: 512 },
1388 DispatchOp::Potrf { p: 64, batch: 1 },
1389 DispatchOp::Potrf { p: 63, batch: 1 },
1390 DispatchOp::Potrf { p: 24, batch: 512 },
1391 DispatchOp::SmallDenseBatchedPotrf { p: 24, batch: 8 },
1392 DispatchOp::SmallDenseBatchedPotrf { p: 24, batch: 7 },
1393 DispatchOp::Trsm { m: 128, n: 64 },
1394 DispatchOp::XtDiagX { n: 50_000, p: 96 },
1395 DispatchOp::XtDiagX { n: 700, p: 24 },
1396 DispatchOp::XtDiagY {
1397 n: 50_000,
1398 px: 96,
1399 q: 8,
1400 },
1401 DispatchOp::JointHessian2x2 {
1402 n: 50_000,
1403 pa: 64,
1404 pb: 64,
1405 },
1406 ];
1407 for policy in &policies {
1408 for op in ops {
1409 let admitted = match op {
1410 DispatchOp::Gemm { m, n, k } => {
1411 op.flops() >= policy.gemm_min_flops as u128 && m.min(n).min(k) > 0
1412 }
1413 DispatchOp::BatchedGemm { batch, m, n, k } => {
1414 op.flops() >= policy.gemm_min_flops as u128
1415 && batch > 1
1416 && m.min(n).min(k) > 0
1417 }
1418 DispatchOp::Gemv { m, k } => {
1419 op.flops() >= policy.gemm_min_flops as u128 && m > 0 && k > 0
1420 }
1421 DispatchOp::Potrf { p, batch } => {
1422 p > 0
1423 && batch > 0
1424 && (p >= policy.potrf_min_p
1425 || (batch > 1 && op.flops() >= policy.gemm_min_flops as u128))
1426 }
1427 DispatchOp::SmallDenseBatchedPotrf { p, batch } => {
1428 p > 0
1429 && p <= policy.small_dense_batched_potrf_max_p
1430 && batch >= policy.small_dense_batched_potrf_min_batch
1431 }
1432 DispatchOp::Trsm { m, n } => {
1433 op.flops() >= policy.gemm_min_flops as u128 && m > 0 && n > 0
1434 }
1435 DispatchOp::XtDiagX { n, p } => policy.xtwx_target_is_gpu(n, p, true),
1436 DispatchOp::XtDiagY { n, px, q } => policy.xtwy_target_is_gpu(n, px, q, true),
1437 DispatchOp::JointHessian2x2 { n, pa, pb } => {
1438 n > 0
1439 && (pa > 0 || pb > 0)
1440 && op.flops() >= policy.gemm_min_flops as u128
1441 }
1442 };
1443 if admitted {
1444 assert!(
1445 op.admissible_under_any_policy(),
1446 "pre-probe bound must not refuse an op the real admission accepts: \
1447 {op:?} under {policy:?}"
1448 );
1449 }
1450 }
1451 }
1452 }
1453}
1454
1455#[cfg(test)]
1456mod tests {
1457 use super::{DispatchOp, route_through_gpu, try_fast_ab};
1458 use crate::GpuPolicy;
1459 use crate::device_runtime::GpuRuntime;
1460
1461 fn available_runtime(label: &str) -> Option<&'static GpuRuntime> {
1462 match GpuRuntime::resolve(GpuPolicy::Auto) {
1463 Ok(runtime) => runtime,
1464 Err(error) => panic!("[{label}] GPU probe fault: {error}"),
1465 }
1466 }
1467
1468 #[test]
1469 fn sae_shape_dispatch_ops_decline_without_cuda_else_route_when_cuda_runtime_is_present() {
1470 let n = 2_000usize;
1471 let p = 2_048usize;
1472 let m = 12usize;
1473 let k = 8usize;
1474 let dense_reduction_ops = [
1475 DispatchOp::XtDiagX { n, p },
1476 DispatchOp::XtDiagY { n, px: p, q: m * k },
1477 DispatchOp::JointHessian2x2 {
1478 n,
1479 pa: p,
1480 pb: m * k,
1481 },
1482 DispatchOp::Gemm {
1483 m: p,
1484 n: p,
1485 k: n * m,
1486 },
1487 ];
1488 let batched_potrf = DispatchOp::SmallDenseBatchedPotrf { p: m, batch: n };
1489 let Some(runtime) = available_runtime("sae dispatch gate") else {
1490 for op in dense_reduction_ops
1491 .iter()
1492 .copied()
1493 .chain(std::iter::once(batched_potrf))
1494 {
1495 assert!(
1496 route_through_gpu(op).is_none(),
1497 "no CUDA runtime is available, yet the SAE dispatch gate admitted {op:?}"
1498 );
1499 }
1500 return;
1501 };
1502
1503 for op in dense_reduction_ops {
1504 assert!(
1505 op.flops() >= runtime.policy.gemm_min_flops as u128,
1506 "SAE dispatch fixture must clear the runtime GEMM work floor: op={op:?}, flops={}, floor={}",
1507 op.flops(),
1508 runtime.policy.gemm_min_flops
1509 );
1510 assert!(
1511 route_through_gpu(op).is_some(),
1512 "SAE dispatch fixture should route to GPU when CUDA is present: {op:?}"
1513 );
1514 }
1515
1516 assert!(
1517 route_through_gpu(batched_potrf).is_some(),
1518 "uniform SAE row blocks should reach the small-dense batched POTRF gate"
1519 );
1520 }
1521
1522 #[test]
1529 fn global_runtime_declines_without_cuda_else_installs_fast_ab_hook_and_matches_cpu() {
1530 use ndarray::Array2;
1531
1532 let (m, k, n) = (512usize, 512usize, 512usize);
1533 let Some(_runtime) = available_runtime("fast_ab hook") else {
1534 assert!(
1535 route_through_gpu(DispatchOp::Gemm { m, n, k }).is_none(),
1536 "no CUDA runtime is available, yet a profitable dense GEMM was admitted"
1537 );
1538 return;
1539 };
1540 assert!(
1542 gam_linalg::gpu_hook::gpu_dispatch().is_some(),
1543 "GpuRuntime::resolve(Auto) returned a device but did not register the \
1544 dense-GEMM dispatch hook — fast_ab would silently stay on the CPU"
1545 );
1546
1547 assert!(
1551 route_through_gpu(DispatchOp::Gemm { m, n, k }).is_some(),
1552 "a 268 MFLOP GEMM must clear the policy floor and route to GPU"
1553 );
1554
1555 let a = Array2::<f64>::from_shape_fn((m, k), |(i, j)| {
1557 ((i * 7 + j * 3) % 13) as f64 * 0.01 - 0.06
1558 });
1559 let b = Array2::<f64>::from_shape_fn((k, n), |(i, j)| {
1560 ((i * 5 + j * 11) % 17) as f64 * 0.01 - 0.08
1561 });
1562
1563 let gpu = try_fast_ab(a.view(), b.view())
1565 .expect("profitable GEMM must produce a device result once admitted");
1566
1567 let mut cpu = Array2::<f64>::zeros((m, n));
1569 for i in 0..m {
1570 for j in 0..n {
1571 let mut acc = 0.0f64;
1572 for p in 0..k {
1573 acc += a[[i, p]] * b[[p, j]];
1574 }
1575 cpu[[i, j]] = acc;
1576 }
1577 }
1578
1579 let mut max_abs = 0.0f64;
1580 for i in 0..m {
1581 for j in 0..n {
1582 max_abs = max_abs.max((gpu[[i, j]] - cpu[[i, j]]).abs());
1583 }
1584 }
1585 assert!(
1586 max_abs < 1e-9,
1587 "device GEMM disagreed with the CPU oracle: max|Δ| = {max_abs:e}"
1588 );
1589 }
1590
1591 #[cfg(target_os = "linux")]
1598 #[test]
1599 fn transpose_free_gemm_declines_without_cuda_else_matches_cpu_all_trans_and_shapes() {
1600 use crate::blas::gemm_cuda;
1601 use ndarray::Array2;
1602
1603 let Some(runtime) = available_runtime("gemm transpose-free") else {
1604 assert!(
1605 route_through_gpu(DispatchOp::Gemm {
1606 m: 512,
1607 n: 512,
1608 k: 512,
1609 })
1610 .is_none(),
1611 "no CUDA runtime is available, yet the transpose-free GEMM seam admitted work"
1612 );
1613 return;
1614 };
1615
1616 let cases = [(6usize, 4usize, 5usize), (17, 23, 9), (200, 31, 7)];
1619 for (m, k, n) in cases {
1620 let mk = Array2::<f64>::from_shape_fn((m, k), |(i, j)| {
1624 ((i * 31 + j * 17) % 19) as f64 * 0.013 - 0.11
1625 });
1626 let km = Array2::<f64>::from_shape_fn((k, m), |(i, j)| {
1627 ((i * 13 + j * 29) % 23) as f64 * 0.011 - 0.07
1628 });
1629 let kn = Array2::<f64>::from_shape_fn((k, n), |(i, j)| {
1630 ((i * 7 + j * 5) % 17) as f64 * 0.017 - 0.09
1631 });
1632 let nk = Array2::<f64>::from_shape_fn((n, k), |(i, j)| {
1633 ((i * 19 + j * 11) % 13) as f64 * 0.015 - 0.05
1634 });
1635
1636 for &trans_a in &[false, true] {
1637 for &trans_b in &[false, true] {
1638 let a = if trans_a { &km } else { &mk };
1639 let b = if trans_b { &nk } else { &kn };
1640
1641 let gpu = gemm_cuda(runtime, a.view(), b.view(), trans_a, trans_b).expect(
1642 "transpose-free device GEMM must produce a result when a device is present",
1643 );
1644 assert_eq!(
1645 gpu.dim(),
1646 (m, n),
1647 "output shape wrong for trans_a={trans_a} trans_b={trans_b} ({m}×{k}×{n})"
1648 );
1649
1650 let mut cpu = Array2::<f64>::zeros((m, n));
1652 for i in 0..m {
1653 for j in 0..n {
1654 let mut acc = 0.0f64;
1655 for p in 0..k {
1656 let av = if trans_a { a[[p, i]] } else { a[[i, p]] };
1657 let bv = if trans_b { b[[j, p]] } else { b[[p, j]] };
1658 acc += av * bv;
1659 }
1660 cpu[[i, j]] = acc;
1661 }
1662 }
1663
1664 let mut max_abs = 0.0f64;
1665 for i in 0..m {
1666 for j in 0..n {
1667 max_abs = max_abs.max((gpu[[i, j]] - cpu[[i, j]]).abs());
1668 }
1669 }
1670 assert!(
1671 max_abs < 1e-9,
1672 "transpose-free GEMM mismatch (trans_a={trans_a} trans_b={trans_b}, \
1673 {m}×{k}×{n}): max|Δ| = {max_abs:e}"
1674 );
1675 }
1676 }
1677 }
1678 }
1679}
1680
1681#[cfg(target_os = "linux")]
1687mod cuda_backend {
1688 use ndarray::{Array1, Array2, Array3, ArrayView1, ArrayView2, ArrayView3};
1699
1700 use super::super::device_runtime::GpuRuntime;
1701 use crate::driver::{from_col_major, to_col_major, to_i32};
1702 use cudarc::cusolver::{DnHandle, sys as cusolver_sys};
1703 use cudarc::driver::{DevicePtrMut, sys as driver_sys};
1704
1705 #[inline]
1706 pub(super) fn gemm(
1707 runtime: &GpuRuntime,
1708 a: ArrayView2<'_, f64>,
1709 b: ArrayView2<'_, f64>,
1710 trans_a: bool,
1711 trans_b: bool,
1712 ) -> Option<Array2<f64>> {
1713 super::super::blas::gemm_cuda(runtime, a, b, trans_a, trans_b)
1714 }
1715
1716 #[inline]
1717 pub(super) fn gemm_on_ordinal(
1718 ordinal: usize,
1719 a: ArrayView2<'_, f64>,
1720 b: ArrayView2<'_, f64>,
1721 trans_a: bool,
1722 trans_b: bool,
1723 ) -> Option<Array2<f64>> {
1724 super::super::blas::gemm_on_ordinal_cuda(ordinal, a, b, trans_a, trans_b)
1725 }
1726
1727 #[inline]
1728 pub(super) fn gemv(
1729 runtime: &GpuRuntime,
1730 a: ArrayView2<'_, f64>,
1731 v: ArrayView1<'_, f64>,
1732 trans_a: bool,
1733 ) -> Option<Array1<f64>> {
1734 super::super::blas::gemv_cuda(runtime, a, v, trans_a)
1735 }
1736
1737 #[inline]
1738 pub(super) fn gemm_broadcast_b_batched(
1739 ordinal: usize,
1740 a: ArrayView3<'_, f64>,
1741 b: ArrayView2<'_, f64>,
1742 ) -> Option<Array3<f64>> {
1743 super::super::blas::gemm_broadcast_b_batched_cuda(ordinal, a, b)
1744 }
1745
1746 #[inline]
1747 pub(super) fn gemm_abt_strided_batched(
1748 ordinal: usize,
1749 a: ArrayView3<'_, f64>,
1750 b: ArrayView3<'_, f64>,
1751 ) -> Option<Array3<f64>> {
1752 super::super::blas::gemm_abt_strided_batched_cuda(ordinal, a, b)
1753 }
1754
1755 #[inline]
1756 pub(super) fn xt_diag_x(
1757 runtime: &GpuRuntime,
1758 x: ArrayView2<'_, f64>,
1759 w: ArrayView1<'_, f64>,
1760 ) -> Option<Array2<f64>> {
1761 super::super::blas::xt_diag_x_cuda(runtime, x, w)
1762 }
1763
1764 #[inline]
1765 pub(super) fn xt_diag_y(
1766 runtime: &GpuRuntime,
1767 x: ArrayView2<'_, f64>,
1768 w: ArrayView1<'_, f64>,
1769 y: ArrayView2<'_, f64>,
1770 ) -> Option<Array2<f64>> {
1771 super::super::blas::xt_diag_y_cuda(runtime, x, w, y)
1772 }
1773
1774 #[inline]
1775 pub(super) fn joint_hessian_2x2(
1776 runtime: &GpuRuntime,
1777 x_a: ArrayView2<'_, f64>,
1778 x_b: ArrayView2<'_, f64>,
1779 w_aa: ArrayView1<'_, f64>,
1780 w_ab: ArrayView1<'_, f64>,
1781 w_bb: ArrayView1<'_, f64>,
1782 ) -> Option<Array2<f64>> {
1783 super::super::blas::joint_hessian_2x2_cuda(runtime, x_a, x_b, w_aa, w_ab, w_bb)
1784 }
1785
1786 #[inline]
1787 pub(super) fn trsm(
1788 runtime: &GpuRuntime,
1789 triangular: ArrayView2<'_, f64>,
1790 rhs: ArrayView2<'_, f64>,
1791 upper: bool,
1792 ) -> Option<Array2<f64>> {
1793 super::super::blas::trsm_cuda(runtime, triangular, rhs, upper)
1794 }
1795
1796 #[inline]
1797 pub(super) fn cholesky_lower(
1798 runtime: &GpuRuntime,
1799 a: ArrayView2<'_, f64>,
1800 ) -> Option<Array2<f64>> {
1801 let (p, p2) = a.dim();
1802 if p == 0 || p != p2 {
1803 return None;
1804 }
1805 let stream = super::super::device_runtime::cuda_context_for(runtime.device.ordinal)?
1806 .new_stream()
1807 .ok()?;
1808 let solver = DnHandle::new(stream.clone()).ok()?;
1809 let a_col = to_col_major(&a);
1810 let mut a_dev = stream.clone_htod(&*a_col).ok()?;
1811 potrf_lower_in_place(&solver, &stream, p, &mut a_dev)?;
1812 let factor_col = stream.clone_dtoh(&a_dev).ok()?;
1813 let mut lower = from_col_major(&factor_col, p, p)?;
1814 for row in 0..p {
1815 for col in (row + 1)..p {
1816 lower[[row, col]] = 0.0;
1817 }
1818 }
1819 Some(lower)
1820 }
1821
1822 #[inline]
1826 pub(super) fn cholesky_batched_lower(
1827 ordinal: usize,
1828 matrices: &mut [Array2<f64>],
1829 ) -> Option<()> {
1830 let first = matrices.first()?;
1831 let p = first.nrows();
1832 if p == 0 || first.ncols() != p || matrices.iter().any(|matrix| matrix.dim() != (p, p)) {
1833 return None;
1834 }
1835
1836 let stream = super::super::device_runtime::cuda_context_for(ordinal)?
1837 .new_stream()
1838 .ok()?;
1839 let solver = DnHandle::new(stream.clone()).ok()?;
1840 let matrix_len = p.checked_mul(p)?;
1841 let mut batch_col = Vec::with_capacity(matrices.len().checked_mul(matrix_len)?);
1842 for matrix in matrices.iter() {
1843 batch_col.extend(to_col_major(&matrix.view()).iter().copied());
1844 }
1845 let mut matrices_dev = stream.clone_htod(&batch_col).ok()?;
1846 let matrix_ptrs = {
1847 let (base_ptr, _matrix_record) = matrices_dev.device_ptr_mut(&stream);
1848 let bytes_per_matrix = driver_sys::CUdeviceptr::try_from(
1849 matrix_len.checked_mul(std::mem::size_of::<f64>())?,
1850 )
1851 .ok()?;
1852 let mut matrix_ptrs = Vec::with_capacity(matrices.len());
1853 for idx in 0..matrices.len() {
1854 let offset = driver_sys::CUdeviceptr::try_from(idx).ok()? * bytes_per_matrix;
1855 matrix_ptrs.push(base_ptr + offset);
1856 }
1857 matrix_ptrs
1858 };
1859 let mut matrix_ptrs_dev = stream.clone_htod(&matrix_ptrs).ok()?;
1860 let mut info_dev = stream.alloc_zeros::<i32>(matrices.len()).ok()?;
1861 let p_i = to_i32(p)?;
1862 let batch_i = to_i32(matrices.len())?;
1863 {
1864 let (ptrs_ptr, _ptrs_record) = matrix_ptrs_dev.device_ptr_mut(&stream);
1865 let (info_ptr, _info_record) = info_dev.device_ptr_mut(&stream);
1866 let status = unsafe {
1870 cusolver_sys::cusolverDnDpotrfBatched(
1871 solver.cu(),
1872 cusolver_sys::cublasFillMode_t::CUBLAS_FILL_MODE_LOWER,
1873 p_i,
1874 ptrs_ptr as *mut *mut f64,
1875 p_i,
1876 info_ptr as *mut i32,
1877 batch_i,
1878 )
1879 };
1880 check_cusolver(status)?;
1881 }
1882 let info_host = stream.clone_dtoh(&info_dev).ok()?;
1883 if info_host.iter().any(|info| *info != 0) {
1884 return None;
1885 }
1886 let factored_col = stream.clone_dtoh(&matrices_dev).ok()?;
1887 for (idx, matrix) in matrices.iter_mut().enumerate() {
1888 let start = idx.checked_mul(matrix_len)?;
1889 let end = start.checked_add(matrix_len)?;
1890 let mut lower = from_col_major(&factored_col[start..end], p, p)?;
1891 for row in 0..p {
1892 for col in (row + 1)..p {
1893 lower[[row, col]] = 0.0;
1894 }
1895 }
1896 *matrix = lower;
1897 }
1898 Some(())
1899 }
1900
1901 fn potrf_lower_in_place(
1907 solver: &DnHandle,
1908 stream: &std::sync::Arc<cudarc::driver::CudaStream>,
1909 p: usize,
1910 a: &mut cudarc::driver::CudaSlice<f64>,
1911 ) -> Option<()> {
1912 crate::solver::potrf_in_place_generic::<f64>(solver, stream, p, a).ok()
1913 }
1914
1915 #[inline]
1916 fn check_cusolver(status: cusolver_sys::cusolverStatus_t) -> Option<()> {
1917 if status == cusolver_sys::cusolverStatus_t::CUSOLVER_STATUS_SUCCESS {
1918 Some(())
1919 } else {
1920 None
1921 }
1922 }
1923}