numr 0.13.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
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
//! Matrix operations: inverse, determinant, trace, diagonal, rank, and norm.

use super::super::client::get_buffer;
use super::super::shaders::linalg as kernels;
use super::super::{WgpuClient, WgpuRuntime};
use crate::algorithm::linalg::{
    MatrixNormOrder, validate_linalg_dtype, validate_matrix_2d, validate_square_matrix,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::{CompareOps, LinalgOps, ReduceOps, ScalarOps, TypeConversionOps, UnaryOps};
use crate::runtime::{AllocGuard, RuntimeClient};
use crate::tensor::Tensor;

pub fn inverse(client: &WgpuClient, a: &Tensor<WgpuRuntime>) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let n = validate_square_matrix(a.shape())?;
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU inverse (only F32 supported)",
        });
    }

    // Compute LU decomposition using decompositions module
    use super::decompositions::lu_decompose;
    let lu_result = lu_decompose(client, a)?;

    // Allocate output and temporary buffers
    let inv_size = n * n * dtype.size_in_bytes();
    let inv_guard = AllocGuard::new(client.allocator(), inv_size)?;
    let inv_ptr = inv_guard.ptr();
    let inv_buffer = get_buffer(inv_ptr)
        .ok_or_else(|| Error::Internal("Failed to get inv buffer".to_string()))?;

    let col_size = n * dtype.size_in_bytes();

    // Create identity matrix on GPU
    let identity_guard = AllocGuard::new(client.allocator(), inv_size)?;
    let identity_ptr = identity_guard.ptr();
    let identity_buffer = get_buffer(identity_ptr)
        .ok_or_else(|| Error::Internal("Failed to get identity buffer".to_string()))?;

    let id_params: [u32; 1] = [n as u32];
    let id_params_buffer = client.create_uniform_buffer("identity_params", 4);
    client.write_buffer(&id_params_buffer, &id_params);

    kernels::launch_create_identity(
        client.pipeline_cache(),
        &client.queue,
        &identity_buffer,
        &id_params_buffer,
        n,
        dtype,
    )?;

    // Get LU and pivots buffers (both already on GPU, no transfers needed)
    let lu_buffer = get_buffer(lu_result.lu.ptr())
        .ok_or_else(|| Error::Internal("Failed to get lu buffer".to_string()))?;
    let pivots_buffer = get_buffer(lu_result.pivots.ptr())
        .ok_or_else(|| Error::Internal("Failed to get pivots buffer".to_string()))?;

    // Allocate temporary buffers
    let e_guard = AllocGuard::new(client.allocator(), col_size)?;
    let e_ptr = e_guard.ptr();
    let pb_guard = AllocGuard::new(client.allocator(), col_size)?;
    let pb_ptr = pb_guard.ptr();
    let y_guard = AllocGuard::new(client.allocator(), col_size)?;
    let y_ptr = y_guard.ptr();
    let x_guard = AllocGuard::new(client.allocator(), col_size)?;
    let x_ptr = x_guard.ptr();

    let e_buffer =
        get_buffer(e_ptr).ok_or_else(|| Error::Internal("Failed to get e buffer".to_string()))?;
    let pb_buffer =
        get_buffer(pb_ptr).ok_or_else(|| Error::Internal("Failed to get pb buffer".to_string()))?;
    let y_buffer =
        get_buffer(y_ptr).ok_or_else(|| Error::Internal("Failed to get y buffer".to_string()))?;
    let x_buffer =
        get_buffer(x_ptr).ok_or_else(|| Error::Internal("Failed to get x buffer".to_string()))?;

    // Solve for each column of the identity matrix
    for col in 0..n {
        // Extract column from identity matrix
        let extract_params: [u32; 3] = [n as u32, n as u32, col as u32];
        let extract_params_buffer = client.create_uniform_buffer("extract_params", 12);
        client.write_buffer(&extract_params_buffer, &extract_params);

        kernels::launch_extract_column(
            client.pipeline_cache(),
            &client.queue,
            &identity_buffer,
            &e_buffer,
            &extract_params_buffer,
            n,
            dtype,
        )?;

        // Apply permutation: pb = P @ e
        let perm_params: [u32; 1] = [n as u32];
        let perm_params_buffer = client.create_uniform_buffer("perm_params", 4);
        client.write_buffer(&perm_params_buffer, &perm_params);

        kernels::launch_apply_lu_permutation(
            client.pipeline_cache(),
            &client.queue,
            &e_buffer,
            &pb_buffer,
            &pivots_buffer,
            &perm_params_buffer,
            dtype,
        )?;

        // Forward substitution: Ly = pb (L has unit diagonal)
        let forward_params: [u32; 2] = [n as u32, 1];
        let forward_params_buffer = client.create_uniform_buffer("forward_params", 8);
        client.write_buffer(&forward_params_buffer, &forward_params);

        kernels::launch_forward_sub(
            client.pipeline_cache(),
            &client.queue,
            &lu_buffer,
            &pb_buffer,
            &y_buffer,
            &forward_params_buffer,
            dtype,
        )?;

        // Backward substitution: Ux = y
        let backward_params: [u32; 1] = [n as u32];
        let backward_params_buffer = client.create_uniform_buffer("backward_params", 4);
        client.write_buffer(&backward_params_buffer, &backward_params);

        kernels::launch_backward_sub(
            client.pipeline_cache(),
            &client.queue,
            &lu_buffer,
            &y_buffer,
            &x_buffer,
            &backward_params_buffer,
            dtype,
        )?;

        // Scatter x into column of inverse matrix
        let scatter_params: [u32; 2] = [n as u32, col as u32];
        let scatter_params_buffer = client.create_uniform_buffer("scatter_params", 8);
        client.write_buffer(&scatter_params_buffer, &scatter_params);

        kernels::launch_scatter_column(
            client.pipeline_cache(),
            &client.queue,
            &x_buffer,
            &inv_buffer,
            &scatter_params_buffer,
            n,
            dtype,
        )?;
    }

    client.synchronize();

    // Guards will automatically deallocate temporary buffers on drop
    drop(identity_guard);
    drop(e_guard);
    drop(pb_guard);
    drop(y_guard);
    drop(x_guard);

    let inv = unsafe { WgpuClient::tensor_from_raw(inv_guard.release(), &[n, n], dtype, device) };

    Ok(inv)
}

pub fn det(client: &WgpuClient, a: &Tensor<WgpuRuntime>) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let n = validate_square_matrix(a.shape())?;
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU det (only F32 supported)",
        });
    }

    // Compute LU decomposition
    use super::decompositions::lu_decompose;
    let lu_result = lu_decompose(client, a)?;

    // Allocate output
    let det_size = dtype.size_in_bytes();
    let det_guard = AllocGuard::new(client.allocator(), det_size)?;
    let det_ptr = det_guard.ptr();
    let det_buffer = get_buffer(det_ptr)
        .ok_or_else(|| Error::Internal("Failed to get det buffer".to_string()))?;

    let lu_buffer = get_buffer(lu_result.lu.ptr())
        .ok_or_else(|| Error::Internal("Failed to get lu buffer".to_string()))?;

    // Create params buffer with n and num_swaps
    let params: [u32; 2] = [n as u32, lu_result.num_swaps as u32];
    let params_buffer = client.create_uniform_buffer("det_params", 8);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_det_from_lu(
        client.pipeline_cache(),
        &client.queue,
        &lu_buffer,
        &det_buffer,
        &params_buffer,
        dtype,
    )?;

    client.synchronize();

    let det = unsafe { WgpuClient::tensor_from_raw(det_guard.release(), &[], dtype, device) };

    Ok(det)
}

pub fn trace(client: &WgpuClient, a: &Tensor<WgpuRuntime>) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (m, n) = validate_matrix_2d(a.shape())?;
    let min_dim = m.min(n);
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU trace (only F32 supported)",
        });
    }

    // Allocate output (zero-initialized for reduction)
    let trace_size = dtype.size_in_bytes();
    let trace_guard = AllocGuard::new(client.allocator(), trace_size)?;
    let trace_ptr = trace_guard.ptr();
    let trace_buffer = get_buffer(trace_ptr)
        .ok_or_else(|| Error::Internal("Failed to get trace buffer".to_string()))?;

    let zero: [f32; 1] = [0.0];
    client.write_buffer(&trace_buffer, &zero);

    let a_buffer =
        get_buffer(a.ptr()).ok_or_else(|| Error::Internal("Failed to get a buffer".to_string()))?;

    let params: [u32; 2] = [min_dim as u32, n as u32];
    let params_buffer = client.create_uniform_buffer("trace_params", 8);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_trace(
        client.pipeline_cache(),
        &client.queue,
        &a_buffer,
        &trace_buffer,
        &params_buffer,
        min_dim,
        dtype,
    )?;

    client.synchronize();

    let trace = unsafe { WgpuClient::tensor_from_raw(trace_guard.release(), &[], dtype, device) };

    Ok(trace)
}

pub fn diag(client: &WgpuClient, a: &Tensor<WgpuRuntime>) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (m, n) = validate_matrix_2d(a.shape())?;
    let min_dim = m.min(n);
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU diag (only F32 supported)",
        });
    }

    let diag_size = min_dim * dtype.size_in_bytes();
    let diag_guard = AllocGuard::new(client.allocator(), diag_size)?;
    let diag_ptr = diag_guard.ptr();
    let diag_buffer = get_buffer(diag_ptr)
        .ok_or_else(|| Error::Internal("Failed to get diag buffer".to_string()))?;

    let a_buffer =
        get_buffer(a.ptr()).ok_or_else(|| Error::Internal("Failed to get a buffer".to_string()))?;

    let params: [u32; 2] = [min_dim as u32, n as u32];
    let params_buffer = client.create_uniform_buffer("diag_params", 8);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_diag(
        client.pipeline_cache(),
        &client.queue,
        &a_buffer,
        &diag_buffer,
        &params_buffer,
        min_dim,
        dtype,
    )?;

    client.synchronize();

    let diag =
        unsafe { WgpuClient::tensor_from_raw(diag_guard.release(), &[min_dim], dtype, device) };

    Ok(diag)
}

pub fn diagflat(client: &WgpuClient, a: &Tensor<WgpuRuntime>) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;

    if a.shape().len() != 1 {
        return Err(Error::Internal(format!(
            "diagflat requires 1D input tensor, got {}D tensor with shape {:?}",
            a.shape().len(),
            a.shape()
        )));
    }

    let n = a.shape()[0];
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU diagflat (only F32 supported)",
        });
    }

    let out_size = n * n * dtype.size_in_bytes();
    let out_guard = AllocGuard::new(client.allocator(), out_size)?;
    let out_ptr = out_guard.ptr();
    let out_buffer = get_buffer(out_ptr)
        .ok_or_else(|| Error::Internal("Failed to get out buffer".to_string()))?;

    let a_buffer =
        get_buffer(a.ptr()).ok_or_else(|| Error::Internal("Failed to get a buffer".to_string()))?;

    let params: [u32; 1] = [n as u32];
    let params_buffer = client.create_uniform_buffer("diagflat_params", 4);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_diagflat(
        client.pipeline_cache(),
        &client.queue,
        &a_buffer,
        &out_buffer,
        &params_buffer,
        n,
        dtype,
    )?;

    client.synchronize();

    let out = unsafe { WgpuClient::tensor_from_raw(out_guard.release(), &[n, n], dtype, device) };

    Ok(out)
}

/// Matrix rank via QR decomposition - runs entirely on GPU (zero CPU transfers)
pub fn matrix_rank(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    tol: Option<f64>,
) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (m, n) = validate_matrix_2d(a.shape())?;
    let dtype = a.dtype();
    let k = m.min(n);

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU matrix_rank (only F32 supported)",
        });
    }

    // Handle empty matrix
    if k == 0 {
        return Tensor::<WgpuRuntime>::from_slice(&[0i64], &[], a.device());
    }

    // Compute tolerance factor (depends only on dimensions, no GPU data needed)
    let base_tol = tol.unwrap_or_else(|| {
        let eps = f32::EPSILON as f64;
        (m.max(n) as f64) * eps
    });

    // Use QR decomposition to estimate rank
    use super::decompositions::qr_decompose_internal;
    let qr = qr_decompose_internal(client, a, false)?;

    // Get diagonal of R
    let r_diag = client.diag(&qr.r)?;

    // Compute abs(r_diag) on GPU
    let abs_diag = client.abs(&r_diag)?;

    // Compute max(abs(r_diag)) on GPU - returns scalar tensor
    let max_val = client.max(&abs_diag, &[], false)?;

    // Compute threshold = base_tol * max on GPU
    let threshold = client.mul_scalar(&max_val, base_tol)?;

    // Compare abs_diag > threshold on GPU (broadcasts threshold)
    let above_mask = client.gt(&abs_diag, &threshold)?;

    // Cast bool mask to F32 for counting (WebGPU sum only supports F32)
    let above_f32 = client.cast(&above_mask, DType::F32)?;

    // Sum to get rank (count of true values)
    let rank_f32 = client.sum(&above_f32, &[], false)?;

    // Cast to I64 for final result
    let rank_tensor = client.cast(&rank_f32, DType::I64)?;

    Ok(rank_tensor)
}

pub fn matrix_norm(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    ord: MatrixNormOrder,
) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    let (_m, _n) = validate_matrix_2d(a.shape())?;
    let dtype = a.dtype();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU matrix_norm (only F32 supported)",
        });
    }

    match ord {
        MatrixNormOrder::Frobenius => {
            // Frobenius norm: ||A||_F = sqrt(sum(A²))
            // Use existing tensor ops to keep data on GPU
            let squared = client.square(a)?;
            let sum_sq = client.sum(&squared, &[], false)?;
            client.sqrt(&sum_sq)
        }
        MatrixNormOrder::Spectral => {
            // Spectral norm is the largest singular value
            use super::svd::svd_decompose;
            let svd = svd_decompose(client, a)?;
            // S is already sorted descending, so max(S) = s[0] = largest singular value
            // Using max keeps computation on GPU (no transfer needed)
            client.max(&svd.s, &[], false)
        }
        MatrixNormOrder::Nuclear => {
            // Nuclear norm is sum of singular values
            use super::svd::svd_decompose;
            let svd = svd_decompose(client, a)?;
            client.sum(&svd.s, &[], false)
        }
    }
}

/// Kronecker product: A āŠ— B
pub fn kron(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    b: &Tensor<WgpuRuntime>,
) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    if a.dtype() != b.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: a.dtype(),
            rhs: b.dtype(),
        });
    }

    let (m_a, n_a) = validate_matrix_2d(a.shape())?;
    let (m_b, n_b) = validate_matrix_2d(b.shape())?;

    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU kron (only F32 supported)",
        });
    }

    let m_out = m_a * m_b;
    let n_out = n_a * n_b;
    let out_size = m_out * n_out * dtype.size_in_bytes();
    let out_guard = AllocGuard::new(client.allocator(), out_size)?;
    let out_ptr = out_guard.ptr();
    let out_buffer = get_buffer(out_ptr)
        .ok_or_else(|| Error::Internal("Failed to get out buffer".to_string()))?;

    let a_buffer =
        get_buffer(a.ptr()).ok_or_else(|| Error::Internal("Failed to get a buffer".to_string()))?;

    let b_buffer =
        get_buffer(b.ptr()).ok_or_else(|| Error::Internal("Failed to get b buffer".to_string()))?;

    let params: [u32; 4] = [m_a as u32, n_a as u32, m_b as u32, n_b as u32];
    let params_buffer = client.create_uniform_buffer("kron_params", 16);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_kron(
        client.pipeline_cache(),
        &client.queue,
        &a_buffer,
        &b_buffer,
        &out_buffer,
        &params_buffer,
        m_a * m_b * n_a * n_b,
        dtype,
    )?;

    client.synchronize();

    let out =
        unsafe { WgpuClient::tensor_from_raw(out_guard.release(), &[m_out, n_out], dtype, device) };

    Ok(out)
}

/// Khatri-Rao product (column-wise Kronecker): A āŠ™ B
///
/// For A of shape [m, k] and B of shape [n, k],
/// produces output of shape [m * n, k].
///
/// (A āŠ™ B)[i*n + j, c] = A[i, c] * B[j, c]
pub fn khatri_rao(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    b: &Tensor<WgpuRuntime>,
) -> Result<Tensor<WgpuRuntime>> {
    validate_linalg_dtype(a.dtype())?;
    if a.dtype() != b.dtype() {
        return Err(Error::DTypeMismatch {
            lhs: a.dtype(),
            rhs: b.dtype(),
        });
    }

    let (m, k_a) = validate_matrix_2d(a.shape())?;
    let (n, k_b) = validate_matrix_2d(b.shape())?;

    if k_a != k_b {
        return Err(Error::Internal(format!(
            "khatri_rao: column count mismatch. A has shape [{}, {}], B has shape [{}, {}]. \
             Matrices must have the same number of columns.",
            m, k_a, n, k_b
        )));
    }

    let k = k_a;
    let dtype = a.dtype();
    let device = client.device();

    if dtype != DType::F32 {
        return Err(Error::UnsupportedDType {
            dtype,
            op: "WGPU khatri_rao (only F32 supported)",
        });
    }

    let m_out = m * n;
    let out_size = m_out * k * dtype.size_in_bytes();
    let out_guard = AllocGuard::new(client.allocator(), out_size)?;
    let out_ptr = out_guard.ptr();
    let out_buffer = get_buffer(out_ptr)
        .ok_or_else(|| Error::Internal("Failed to get out buffer".to_string()))?;

    let a_buffer =
        get_buffer(a.ptr()).ok_or_else(|| Error::Internal("Failed to get a buffer".to_string()))?;

    let b_buffer =
        get_buffer(b.ptr()).ok_or_else(|| Error::Internal("Failed to get b buffer".to_string()))?;

    // params: [m, n, k, _pad]
    let params: [u32; 4] = [m as u32, n as u32, k as u32, 0];
    let params_buffer = client.create_uniform_buffer("khatri_rao_params", 16);
    client.write_buffer(&params_buffer, &params);

    kernels::launch_khatri_rao(
        client.pipeline_cache(),
        &client.queue,
        &a_buffer,
        &b_buffer,
        &out_buffer,
        &params_buffer,
        m_out * k,
        dtype,
    )?;

    client.synchronize();

    let out =
        unsafe { WgpuClient::tensor_from_raw(out_guard.release(), &[m_out, k], dtype, device) };

    Ok(out)
}

/// Upper triangular part of a matrix — delegates to impl_generic
pub fn triu(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    diagonal: i64,
) -> Result<Tensor<WgpuRuntime>> {
    crate::ops::impl_generic::triu_impl(client, a, diagonal)
}

/// Lower triangular part of a matrix — delegates to impl_generic
pub fn tril(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
    diagonal: i64,
) -> Result<Tensor<WgpuRuntime>> {
    crate::ops::impl_generic::tril_impl(client, a, diagonal)
}

/// Sign and log-absolute-determinant — delegates to impl_generic
pub fn slogdet(
    client: &WgpuClient,
    a: &Tensor<WgpuRuntime>,
) -> Result<crate::algorithm::linalg::SlogdetResult<WgpuRuntime>> {
    crate::ops::impl_generic::slogdet_impl(client, a)
}

#[cfg(test)]
mod tests {
    use super::super::test_support::*;
    use super::WgpuRuntime;
    use crate::algorithm::LinearAlgebraAlgorithms;
    use crate::runtime::RuntimeClient;
    use crate::runtime::wgpu::is_wgpu_available;
    use crate::tensor::Tensor;

    #[test]
    fn test_trace() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // 2x2 matrix: [[1, 2], [3, 4]]
        // trace = 1 + 4 = 5
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();

        let t = client.trace(&a).unwrap();
        let result: Vec<f32> = t.to_vec();

        assert!((result[0] - 5.0).abs() < 1e-5);
    }

    #[test]
    fn test_diag() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // 2x3 matrix
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3], device)
                .unwrap();

        let d = client.diag(&a).unwrap();
        let result: Vec<f32> = d.to_vec();

        assert_eq!(result.len(), 2);
        assert!((result[0] - 1.0).abs() < 1e-5);
        assert!((result[1] - 5.0).abs() < 1e-5);
    }

    #[test]
    fn test_diagflat() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        let a = Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0], &[3], device).unwrap();

        let m = client.diagflat(&a).unwrap();
        let result: Vec<f32> = m.to_vec();

        assert_eq!(m.shape(), &[3, 3]);
        // Expected: [[1, 0, 0], [0, 2, 0], [0, 0, 3]]
        assert!((result[0] - 1.0).abs() < 1e-5); // [0,0]
        assert!((result[1]).abs() < 1e-5); // [0,1]
        assert!((result[4] - 2.0).abs() < 1e-5); // [1,1]
        assert!((result[8] - 3.0).abs() < 1e-5); // [2,2]
    }

    #[test]
    fn test_det() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // 2x2 matrix: [[1, 2], [3, 4]]
        // det = 1*4 - 2*3 = -2
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();

        let d = client.det(&a).unwrap();
        let result: Vec<f32> = d.to_vec();

        assert!((result[0] - (-2.0)).abs() < 1e-4);
    }

    #[test]
    fn test_inverse() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // Test 2x2 matrix: [[4, 7], [2, 6]]
        // Inverse: [[0.6, -0.7], [-0.2, 0.4]]
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[4.0f32, 7.0, 2.0, 6.0], &[2, 2], device).unwrap();

        let inv = client.inverse(&a).unwrap();
        let result: Vec<f32> = inv.to_vec();

        // Check inverse values (det = 4*6 - 7*2 = 10)
        // inv = (1/10) * [[6, -7], [-2, 4]]
        assert!((result[0] - 0.6).abs() < 1e-4); // [0,0]
        assert!((result[1] - (-0.7)).abs() < 1e-4); // [0,1]
        assert!((result[2] - (-0.2)).abs() < 1e-4); // [1,0]
        assert!((result[3] - 0.4).abs() < 1e-4); // [1,1]
    }

    #[test]
    fn test_matrix_rank_full() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // Full rank 2x2 matrix
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();

        let rank = client.matrix_rank(&a, None).unwrap();
        let result: Vec<i64> = rank.to_vec();

        assert_eq!(result[0], 2);
    }

    #[test]
    fn test_matrix_rank_deficient() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // Rank-deficient 2x2 matrix (rows are linearly dependent)
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 2.0, 4.0], &[2, 2], device).unwrap();

        let rank = client.matrix_rank(&a, None).unwrap();
        let result: Vec<i64> = rank.to_vec();

        assert_eq!(result[0], 1);
    }

    #[test]
    fn test_kron_2x2() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // A = [[1, 2], [3, 4]], B = [[0, 5], [6, 7]]
        let a =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], device).unwrap();
        let b =
            Tensor::<WgpuRuntime>::from_slice(&[0.0f32, 5.0, 6.0, 7.0], &[2, 2], device).unwrap();

        let kron = client.kron(&a, &b).unwrap();
        assert_eq!(kron.shape(), &[4, 4]);

        let data: Vec<f32> = kron.to_vec();

        // Expected result:
        // [[0,  5,  0, 10],
        //  [6,  7, 12, 14],
        //  [0, 15,  0, 20],
        //  [18, 21, 24, 28]]
        #[rustfmt::skip]
        let expected: [f32; 16] = [
            0.0, 5.0, 0.0, 10.0,
            6.0, 7.0, 12.0, 14.0,
            0.0, 15.0, 0.0, 20.0,
            18.0, 21.0, 24.0, 28.0,
        ];

        for (i, (got, exp)) in data.iter().zip(expected.iter()).enumerate() {
            assert!(
                (got - exp).abs() < 1e-4,
                "element {} differs: {} vs {}",
                i,
                got,
                exp
            );
        }
    }

    #[test]
    fn test_kron_identity() {
        if !is_wgpu_available() {
            println!("No GPU available, skipping test");
            return;
        }

        let client = create_client();
        let device = client.device();

        // Iā‚‚ āŠ— Iā‚‚ = Iā‚„
        let i2 =
            Tensor::<WgpuRuntime>::from_slice(&[1.0f32, 0.0, 0.0, 1.0], &[2, 2], device).unwrap();

        let kron = client.kron(&i2, &i2).unwrap();
        assert_eq!(kron.shape(), &[4, 4]);

        let data: Vec<f32> = kron.to_vec();

        // Should be 4x4 identity
        for i in 0..4 {
            for j in 0..4 {
                let expected = if i == j { 1.0 } else { 0.0 };
                assert!(
                    (data[i * 4 + j] - expected).abs() < 1e-5,
                    "kron[{},{}] = {} expected {}",
                    i,
                    j,
                    data[i * 4 + j],
                    expected
                );
            }
        }
    }
}