primal-barracuda 0.4.0

barraCuda — BARrier-free Rust Abstracted Cross-platform Unified Dimensional Algebra. Vendor-agnostic GPU compute via WGSL.
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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Compute Kernel Routing - Unified Math Language → Hardware-Specific Implementation
//!
//! **Evolution (Feb 15, 2026)**: Completes the NPU pipeline!
//!
//! This module implements the "compile/adjust" layer for routing math
//! to the appropriate hardware:
//!
//! - **GPU/CPU**: WGSL shaders run directly (our unified math language)
//! - **NPU**: Route to pre-compiled models if workload matches NPU capability
//! - **TPU**: (Future) Route to TPU-specific operations
//!
//! # Philosophy
//!
//! barraCuda treats WGSL as the "unified math language" for arbitrary computation.
//! When a workload can be accelerated by specialized hardware, we route to
//! hardware-specific implementations. Otherwise, WGSL runs on GPU/CPU.
//!
//! This is NOT a compiler (WGSL → NPU bytecode). NPUs run pre-compiled models,
//! not arbitrary code. The routing layer matches workloads to available
//! hardware capabilities.
//!
//! # Example
//!
//! ```no_run
//! use barracuda::device::kernel_router::{KernelRouter, ComputeWorkload, KernelTarget};
//!
//! # fn main() -> barracuda::error::Result<()> {
//! let router = KernelRouter::new()?;
//! let workload = ComputeWorkload::SparseInference {
//!     input_sparsity: 0.95,
//!     model_name: "edge_classifier".to_string(),
//! };
//! let target = router.route(&workload)?;
//! match target {
//!     KernelTarget::Npu { model_id: _, .. } => {}
//!     KernelTarget::Wgsl { shader: _, device: _, .. } => {}
//!     KernelTarget::Hybrid { .. } => {}
//! }
//! # Ok(())
//! # }
//! ```

use crate::device::backend::HardwareHint;
use crate::device::{Device, DeviceSelection};
use crate::error::Result;
use std::collections::HashMap;

/// Precision hint for matmul workloads — determines tensor-core eligibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MatmulPrecision {
    /// Standard 32-bit float (ALU/FP32 cores).
    F32,
    /// Half-precision — tensor-core eligible on SM70+.
    F16,
    /// Brain floating point — tensor-core eligible on SM80+.
    Bf16,
    /// TensorFloat-32 — tensor-core eligible on SM80+ with 19-bit mantissa.
    Tf32,
    /// 64-bit float — always ALU compute path.
    F64,
}

impl MatmulPrecision {
    /// Whether this precision can route through tensor cores (MMA/HMMA/WGMMA).
    #[must_use]
    pub const fn is_tensor_core_eligible(self) -> bool {
        matches!(self, Self::F16 | Self::Bf16 | Self::Tf32)
    }
}

/// Workloads smaller than this use CPU to avoid GPU dispatch overhead.
const CPU_FALLBACK_THRESHOLD: usize = 1_000;

/// Eigendecomposition matrices smaller than this route to CPU.
const EIGENDECOMP_CPU_THRESHOLD: usize = 128;

/// Linear systems smaller than this route to CPU.
const LINEAR_SOLVE_CPU_THRESHOLD: usize = 256;

/// Matmul dimensions above which 16x16 tile workgroup is used.
const MATMUL_LARGE_DIM: usize = 256;

/// Matmul dimensions above which 8x8 tile workgroup is used.
const MATMUL_MEDIUM_DIM: usize = 64;

/// Default 1D workgroup size for FFT and binary prescreen shaders.
const WORKGROUP_FFT: [u32; 3] = [256, 1, 1];

/// Default 1D workgroup size for physics force computations.
const WORKGROUP_PHYSICS: [u32; 3] = [64, 1, 1];

/// Compute workload description
///
/// Describes WHAT computation needs to be done, not HOW.
/// The router decides which hardware to target.
#[derive(Debug, Clone)]
pub enum ComputeWorkload {
    /// Dense matrix operations (matmul, conv) — routes to tensor cores when
    /// precision is F16/BF16/TF32 and hardware supports MMA instructions.
    DenseMatmul {
        /// Rows of output matrix (M)
        m: usize,
        /// Columns of output matrix (N)
        n: usize,
        /// Inner dimension (K)
        k: usize,
        /// Optional precision hint — enables tensor-core routing for F16/BF16/TF32.
        /// `None` defaults to F32 (standard compute path).
        precision: Option<MatmulPrecision>,
    },

    /// Sparse inference with high input sparsity - NPU preferred
    SparseInference {
        /// Input sparsity ratio (0.0 = dense, 1.0 = empty)
        input_sparsity: f64,
        /// Model identifier (for NPU model lookup)
        model_name: String,
    },

    /// Reservoir computing / Echo State Network - NPU natural fit
    ReservoirState {
        /// Reservoir size
        reservoir_size: usize,
        /// Input dimension
        input_dim: usize,
    },

    /// FFT computation - always GPU (butterfly stages are parallel)
    FFT {
        /// FFT size (number of points)
        size: usize,
        /// Number of batched FFTs
        batch_count: usize,
    },

    /// Physics force computation - always GPU (needs arbitrary WGSL)
    PhysicsForce {
        /// Number of particles
        particle_count: usize,
        /// Force kernel name (e.g. "`lennard_jones`")
        force_type: String,
    },

    /// Eigenvalue decomposition - GPU for large, CPU for small
    Eigendecomp {
        /// Matrix dimension (N×N)
        matrix_size: usize,
    },

    /// Linear system solve - GPU for large, CPU for small
    LinearSolve {
        /// System dimension (N×N)
        system_size: usize,
    },

    /// Binary pre-screening / filtering - NPU ideal (ultra-low power)
    BinaryPrescreen {
        /// Number of inputs to screen
        input_count: usize,
        /// Threshold for binary decision
        threshold: f64,
    },

    /// Generic WGSL operation - always GPU/CPU
    GenericWgsl {
        /// Shader module name or path
        shader_name: String,
    },
}

/// Target hardware for kernel execution
#[derive(Debug, Clone)]
pub enum KernelTarget {
    /// Run on NPU with pre-compiled model
    Npu {
        /// Model file path or ID
        model_id: String,
        /// Expected input shape
        input_shape: Vec<usize>,
        /// Expected output shape
        output_shape: Vec<usize>,
    },

    /// Run WGSL shader on GPU or CPU
    Wgsl {
        /// Shader name/path
        shader: String,
        /// Target device (GPU or CPU)
        device: DeviceSelection,
        /// Workgroup size hint
        workgroup_size: [u32; 3],
    },

    /// Hybrid: NPU for preprocessing, GPU for main compute
    Hybrid {
        /// NPU model for sparse filtering
        npu_prefilter: Option<String>,
        /// WGSL shader for dense compute
        wgsl_compute: String,
        /// Target device for WGSL
        device: DeviceSelection,
    },

    /// Sovereign dispatch via toadStool IPC — tensor-core or specialized hardware.
    /// Used when the workload needs MMA instructions (HMMA/WGMMA) that cannot
    /// be expressed in WGSL and require coralReef native codegen + toadStool dispatch.
    Sovereign {
        /// Shader path or identifier for coralReef compilation.
        shader: String,
        /// Target device (always GPU for sovereign).
        device: DeviceSelection,
        /// Hardware unit hint for toadStool dispatch.
        hardware_hint: HardwareHint,
        /// Workgroup size hint.
        workgroup_size: [u32; 3],
    },
}

/// Kernel router - maps workloads to hardware
///
/// The router knows what hardware is available and which workloads
/// each device can accelerate. It returns the best target for a given
/// computation.
pub struct KernelRouter {
    /// Available NPU models (`model_name` → `model_path`)
    npu_models: HashMap<String, NpuModelInfo>,
    /// GPU available
    has_gpu: bool,
    /// NPU available
    has_npu: bool,
    has_tpu: bool,
}

/// NPU model metadata discovered from `.fbz` files on disk.
///
/// Shapes default to conservative estimates when the model's internal
/// metadata cannot be parsed. The router uses these for work-sizing
/// heuristics only — actual execution reads shapes from the model binary.
#[derive(Debug, Clone)]
pub struct NpuModelInfo {
    /// Model file path
    pub path: String,
    /// Input shape (estimated from filename convention or model header)
    pub input_shape: Vec<usize>,
    /// Output shape (estimated from filename convention or model header)
    pub output_shape: Vec<usize>,
    /// Sparsity threshold for efficient execution on NPU
    pub sparsity_threshold: f64,
}

/// Default shape estimates when model metadata is unavailable.
const DEFAULT_NPU_INPUT_DIM: usize = 128;
const DEFAULT_NPU_OUTPUT_DIM: usize = 10;
const DEFAULT_SPARSITY_THRESHOLD: f64 = 0.7;

impl NpuModelInfo {
    /// Construct from a discovered filesystem path with default shape estimates.
    fn from_discovered_path(path: String) -> Self {
        Self {
            path,
            input_shape: vec![DEFAULT_NPU_INPUT_DIM],
            output_shape: vec![DEFAULT_NPU_OUTPUT_DIM],
            sparsity_threshold: DEFAULT_SPARSITY_THRESHOLD,
        }
    }
}

impl KernelRouter {
    /// Create new kernel router with runtime hardware discovery
    /// # Errors
    /// Returns [`Err`] if NPU model discovery fails (e.g. filesystem or
    /// permission errors).
    pub fn new() -> Result<Self> {
        let has_gpu = Device::GPU.is_available();
        let has_npu = Device::NPU.is_available();
        let has_tpu = Device::TPU.is_available();

        // Discover available NPU models
        let npu_models = Self::discover_npu_models()?;

        Ok(Self {
            npu_models,
            has_gpu,
            has_npu,
            has_tpu,
        })
    }

    /// Whether a TPU is available for routing.
    #[must_use]
    pub fn has_tpu(&self) -> bool {
        self.has_tpu
    }

    /// Route workload to best hardware target
    /// # Errors
    /// Returns [`Err`] if workload routing fails (e.g. device unavailable or
    /// capability check fails).
    pub fn route(&self, workload: &ComputeWorkload) -> Result<KernelTarget> {
        match workload {
            // === Dense matmul → tensor-core sovereign when eligible, else WGSL ===
            ComputeWorkload::DenseMatmul { m, n, k, precision } => {
                let size = m * n * k;

                if let Some(prec) = precision
                    && prec.is_tensor_core_eligible()
                    && self.has_gpu
                {
                    return Ok(KernelTarget::Sovereign {
                        shader: "matmul_mma".to_string(),
                        device: DeviceSelection::Gpu,
                        hardware_hint: HardwareHint::TensorCore,
                        workgroup_size: self.optimal_workgroup_for_matmul(*m, *n, *k),
                    });
                }

                let device = self.select_wgsl_device(size);
                Ok(KernelTarget::Wgsl {
                    shader: "matmul".to_string(),
                    device,
                    workgroup_size: self.optimal_workgroup_for_matmul(*m, *n, *k),
                })
            }

            ComputeWorkload::FFT { size, batch_count } => {
                let total = size * batch_count;
                let device = self.select_wgsl_device(total);
                Ok(KernelTarget::Wgsl {
                    shader: "fft".to_string(),
                    device,
                    workgroup_size: WORKGROUP_FFT,
                })
            }

            ComputeWorkload::PhysicsForce {
                particle_count,
                force_type,
            } => {
                let device = self.select_wgsl_device(*particle_count);
                Ok(KernelTarget::Wgsl {
                    shader: format!("forces/{force_type}"),
                    device,
                    workgroup_size: WORKGROUP_PHYSICS,
                })
            }

            ComputeWorkload::Eigendecomp { matrix_size } => {
                let device = if *matrix_size < EIGENDECOMP_CPU_THRESHOLD {
                    DeviceSelection::Cpu
                } else {
                    self.select_wgsl_device(matrix_size * matrix_size)
                };
                Ok(KernelTarget::Wgsl {
                    shader: "linalg/eigh".to_string(),
                    device,
                    workgroup_size: [16, 16, 1],
                })
            }

            ComputeWorkload::LinearSolve { system_size } => {
                let device = if *system_size < LINEAR_SOLVE_CPU_THRESHOLD {
                    DeviceSelection::Cpu
                } else {
                    self.select_wgsl_device(system_size * system_size)
                };
                Ok(KernelTarget::Wgsl {
                    shader: "linalg/solve".to_string(),
                    device,
                    workgroup_size: [16, 16, 1],
                })
            }

            ComputeWorkload::GenericWgsl { shader_name } => {
                let device = self.select_wgsl_device(CPU_FALLBACK_THRESHOLD);
                Ok(KernelTarget::Wgsl {
                    shader: shader_name.clone(),
                    device,
                    workgroup_size: [64, 1, 1],
                })
            }

            // === Sparse/Event workloads → NPU preferred if available ===
            ComputeWorkload::SparseInference {
                input_sparsity,
                model_name,
            } => {
                // NPU: if available AND we have the model AND sparsity is high enough
                if self.has_npu
                    && let Some(model_info) = self.npu_models.get(model_name)
                    && *input_sparsity >= model_info.sparsity_threshold
                {
                    return Ok(KernelTarget::Npu {
                        model_id: model_info.path.clone(),
                        input_shape: model_info.input_shape.clone(),
                        output_shape: model_info.output_shape.clone(),
                    });
                }
                let device = self.select_wgsl_device(CPU_FALLBACK_THRESHOLD * 10);
                Ok(KernelTarget::Wgsl {
                    shader: format!("snn/{model_name}"),
                    device,
                    workgroup_size: [64, 1, 1],
                })
            }

            ComputeWorkload::ReservoirState {
                reservoir_size,
                input_dim,
            } => {
                // NPU: natural fit for reservoir computing (event-driven)
                if self.has_npu
                    && let Some(model_info) = self.npu_models.get("reservoir")
                {
                    return Ok(KernelTarget::Npu {
                        model_id: model_info.path.clone(),
                        input_shape: vec![*input_dim],
                        output_shape: vec![*reservoir_size],
                    });
                }
                // Fallback: WGSL reservoir simulation
                let device = self.select_wgsl_device(reservoir_size * input_dim);
                Ok(KernelTarget::Wgsl {
                    shader: "reservoir/esn".to_string(),
                    device,
                    workgroup_size: [64, 1, 1],
                })
            }

            ComputeWorkload::BinaryPrescreen {
                input_count,
                threshold: _,
            } => {
                // NPU: ideal for binary pre-screening (ultra-low power)
                if self.has_npu
                    && let Some(model_info) = self.npu_models.get("prescreen")
                {
                    return Ok(KernelTarget::Npu {
                        model_id: model_info.path.clone(),
                        input_shape: vec![*input_count],
                        output_shape: vec![*input_count],
                    });
                }
                // Fallback: simple threshold on GPU
                let device = self.select_wgsl_device(*input_count);
                Ok(KernelTarget::Wgsl {
                    shader: "prescreen/binary_threshold".to_string(),
                    device,
                    workgroup_size: WORKGROUP_FFT,
                })
            }
        }
    }

    /// Check if a workload CAN be accelerated by NPU
    #[must_use]
    pub fn can_route_to_npu(&self, workload: &ComputeWorkload) -> bool {
        if !self.has_npu {
            return false;
        }

        match workload {
            ComputeWorkload::SparseInference { model_name, .. } => {
                self.npu_models.contains_key(model_name)
            }
            ComputeWorkload::ReservoirState { .. } => self.npu_models.contains_key("reservoir"),
            ComputeWorkload::BinaryPrescreen { .. } => self.npu_models.contains_key("prescreen"),
            // Dense compute cannot go to NPU
            _ => false,
        }
    }

    /// Select best WGSL device (GPU or CPU)
    fn select_wgsl_device(&self, workload_size: usize) -> DeviceSelection {
        if workload_size < CPU_FALLBACK_THRESHOLD {
            return DeviceSelection::Cpu;
        }
        if self.has_gpu {
            DeviceSelection::Gpu
        } else {
            DeviceSelection::Cpu
        }
    }

    /// Optimal workgroup size for matmul
    fn optimal_workgroup_for_matmul(&self, m: usize, n: usize, _k: usize) -> [u32; 3] {
        if m >= MATMUL_LARGE_DIM && n >= MATMUL_LARGE_DIM {
            [16, 16, 1]
        } else if m >= MATMUL_MEDIUM_DIM && n >= MATMUL_MEDIUM_DIM {
            [8, 8, 1]
        } else {
            [4, 4, 1]
        }
    }

    /// Discover available NPU models via capability-based filesystem search.
    ///
    /// Resolution chain (first match wins):
    /// 1. `AKIDA_MODEL_PATH` environment variable
    /// 2. `AKIDA_HOME` + `/models` if set
    /// 3. `AKIDA_MODELS_DIR` environment variable
    /// 4. XDG data dirs
    /// 5. System paths: `/opt/akida/models`, `/usr/local/akida/models`, `/usr/share/akida/models`
    fn discover_npu_models() -> Result<HashMap<String, NpuModelInfo>> {
        let mut models = HashMap::new();

        for dir in super::akida::akida_model_dirs() {
            let path = dir.as_path();
            if path.exists()
                && let Ok(entries) = std::fs::read_dir(path)
            {
                for entry in entries.flatten() {
                    if let Some(ext) = entry.path().extension()
                        && ext == "fbz"
                    {
                        // Found a model - extract metadata
                        if let Some(name) = entry.path().file_stem() {
                            let model_name = name.to_string_lossy().to_string();
                            models.insert(
                                model_name.clone(),
                                NpuModelInfo::from_discovered_path(
                                    entry.path().to_string_lossy().to_string(),
                                ),
                            );
                        }
                    }
                }
            }
        }

        Ok(models)
    }

    /// Register a custom NPU model
    pub fn register_npu_model(&mut self, name: &str, info: NpuModelInfo) {
        self.npu_models.insert(name.to_string(), info);
    }

    /// Get list of available NPU model names.
    #[must_use]
    pub fn available_npu_models(&self) -> Vec<&str> {
        self.npu_models
            .keys()
            .map(std::string::String::as_str)
            .collect()
    }
}

impl Default for KernelRouter {
    fn default() -> Self {
        Self::new().unwrap_or_else(|e| {
            tracing::warn!(
                error = %e,
                "KernelRouter: NPU discovery failed, routing without NPU models"
            );
            Self {
                npu_models: HashMap::new(),
                has_gpu: Device::GPU.is_available(),
                has_npu: false,
                has_tpu: false,
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_kernel_router_creation() {
        let router = KernelRouter::new();
        assert!(router.is_ok());
    }

    #[test]
    fn test_dense_matmul_routes_to_wgsl() {
        let router = KernelRouter::default();
        let workload = ComputeWorkload::DenseMatmul {
            m: 1024,
            n: 1024,
            k: 1024,
            precision: None,
        };
        let target = router.route(&workload).unwrap();
        match target {
            KernelTarget::Wgsl { shader, device, .. } => {
                assert_eq!(shader, "matmul");
                assert!(device.supports_wgsl());
            }
            _ => panic!("Dense matmul (f32) should route to WGSL"),
        }
    }

    #[test]
    fn test_dense_matmul_f16_routes_to_sovereign_tensor_core() {
        let router = KernelRouter::default();
        let workload = ComputeWorkload::DenseMatmul {
            m: 1024,
            n: 1024,
            k: 1024,
            precision: Some(MatmulPrecision::F16),
        };
        let target = router.route(&workload).unwrap();
        match target {
            KernelTarget::Sovereign {
                hardware_hint,
                shader,
                ..
            } => {
                assert_eq!(hardware_hint, HardwareHint::TensorCore);
                assert_eq!(shader, "matmul_mma");
            }
            KernelTarget::Wgsl { .. } => {
                // Falls back to WGSL if no GPU available in CI
            }
            _ => panic!("F16 matmul should route to Sovereign/TensorCore or Wgsl"),
        }
    }

    #[test]
    fn test_dense_matmul_f64_routes_to_wgsl() {
        let router = KernelRouter::default();
        let workload = ComputeWorkload::DenseMatmul {
            m: 512,
            n: 512,
            k: 512,
            precision: Some(MatmulPrecision::F64),
        };
        let target = router.route(&workload).unwrap();
        match target {
            KernelTarget::Wgsl { shader, .. } => {
                assert_eq!(shader, "matmul");
            }
            _ => panic!("F64 matmul should route to WGSL compute path"),
        }
    }

    #[test]
    fn test_physics_force_routes_to_wgsl() {
        let router = KernelRouter::default();
        let workload = ComputeWorkload::PhysicsForce {
            particle_count: 10_000,
            force_type: "lennard_jones".to_string(),
        };
        let target = router.route(&workload).unwrap();
        match target {
            KernelTarget::Wgsl { device, .. } => {
                assert!(device.supports_wgsl());
            }
            _ => panic!("Physics force should route to WGSL"),
        }
    }

    #[test]
    fn test_small_eigendecomp_routes_to_cpu() {
        let router = KernelRouter::default();
        let workload = ComputeWorkload::Eigendecomp { matrix_size: 32 };
        let target = router.route(&workload).unwrap();
        match target {
            KernelTarget::Wgsl { device, .. } => {
                assert_eq!(device, DeviceSelection::Cpu);
            }
            _ => panic!("Small eigendecomp should route to CPU"),
        }
    }

    #[test]
    fn test_sparse_inference_fallback() {
        let router = KernelRouter::default(); // No NPU models registered
        let workload = ComputeWorkload::SparseInference {
            input_sparsity: 0.95,
            model_name: "nonexistent".to_string(),
        };
        let target = router.route(&workload).unwrap();
        // Should fall back to WGSL
        match target {
            KernelTarget::Wgsl { .. } => {}
            _ => panic!("Missing NPU model should fall back to WGSL"),
        }
    }

    #[test]
    fn test_can_route_to_npu() {
        let router = KernelRouter::default();

        // Without NPU models, nothing can route to NPU
        let workload = ComputeWorkload::SparseInference {
            input_sparsity: 0.95,
            model_name: "test".to_string(),
        };
        // NPU not available in default router
        assert!(!router.can_route_to_npu(&workload));

        // Dense matmul can never route to NPU
        let dense = ComputeWorkload::DenseMatmul {
            m: 1024,
            n: 1024,
            k: 1024,
            precision: None,
        };
        assert!(!router.can_route_to_npu(&dense));
    }

    #[test]
    fn test_register_npu_model() {
        let mut router = KernelRouter::default();
        router.register_npu_model(
            "custom_model",
            NpuModelInfo {
                path: "/path/to/model.fbz".to_string(),
                input_shape: vec![128],
                output_shape: vec![10],
                sparsity_threshold: 0.8,
            },
        );
        assert!(router.available_npu_models().contains(&"custom_model"));
    }
}