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
// SPDX-License-Identifier: AGPL-3.0-or-later
// ! Akida NPU Backend for barraCuda
//!
//! Provides Akida-specific acceleration for neuromorphic operations
//! while maintaining compatibility with the universal barraCuda API.
//!
//! **Architecture**:
//! - Detects available Akida boards
//! - Translates select operations to Akida-native format
//! - Falls back to wgpu for non-neuromorphic operations
//! - Maintains zero hardcoding principle

use crate::error::Result;
use std::path::PathBuf;

/// Akida board information
#[derive(Debug, Clone)]
pub struct AkidaBoard {
    /// Board index (0-based)
    pub index: usize,

    /// `PCIe` address (e.g., "a1:00.0")
    pub pcie_address: String,

    /// Device path (e.g., "/dev/akida0")
    pub device_path: PathBuf,

    /// Chip name (e.g., "Akida AKD1000")
    pub chip_name: String,

    /// Number of NPUs
    pub npu_count: usize,

    /// Available memory in bytes
    pub memory_bytes: usize,

    /// Current power consumption (watts)
    pub power_watts: f64,

    /// Current temperature (celsius)
    pub temperature_celsius: f64,

    /// `PCIe` generation (1-4)
    pub pcie_generation: u8,

    /// `PCIe` lane count
    pub pcie_lanes: u8,

    /// Health status
    pub health: BoardHealth,
}

/// Board health status
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardHealth {
    /// Operating normally
    Healthy,

    /// Operating with warnings (high temp, etc.)
    Warning,

    /// Not responding or critical error
    Critical,

    /// Not yet queried
    Unknown,
}

/// Akida backend capabilities
#[derive(Debug, Clone)]
pub struct AkidaCapabilities {
    /// Boards detected
    pub boards: Vec<AkidaBoard>,

    /// Total NPUs across all boards
    pub total_npus: usize,

    /// Total memory across all boards
    pub total_memory_bytes: usize,

    /// SDK version (if available)
    pub sdk_version: Option<String>,
}

/// Detect available Akida boards
///
/// **Deep Debt**: Runtime discovery, zero hardcoding
///
/// # Errors
///
/// Returns [`Err`] if `PCIe` scanning fails or board query fails (e.g. permission
/// denied, driver unavailable).
pub fn detect_akida_boards() -> Result<AkidaCapabilities> {
    tracing::info!("Detecting Akida NPU boards...");

    // Scan PCIe bus for BrainChip devices
    let pcie_devices = scan_pcie_for_akida()?;

    if pcie_devices.is_empty() {
        tracing::info!("No Akida boards detected");
        return Ok(AkidaCapabilities {
            boards: Vec::new(),
            total_npus: 0,
            total_memory_bytes: 0,
            sdk_version: None,
        });
    }

    tracing::info!("Found {} Akida board(s)", pcie_devices.len());

    // Query each board
    let boards: Vec<_> = pcie_devices
        .iter()
        .enumerate()
        .filter_map(|(index, device)| match query_board_info(device, index) {
            Ok(board) => {
                tracing::info!(
                    "  Board {}: {} at {} ({} NPUs, {:.1}W, {:.1}°C)",
                    index,
                    board.chip_name,
                    board.pcie_address,
                    board.npu_count,
                    board.power_watts,
                    board.temperature_celsius
                );
                Some(board)
            }
            Err(e) => {
                tracing::warn!("Failed to query board {}: {}", index, e);
                None
            }
        })
        .collect();

    // Calculate totals
    let total_npus = boards.iter().map(|b| b.npu_count).sum();
    let total_memory_bytes = boards.iter().map(|b| b.memory_bytes).sum();

    // Try to detect SDK version
    let sdk_version = detect_akida_sdk_version();

    Ok(AkidaCapabilities {
        boards,
        total_npus,
        total_memory_bytes,
        sdk_version,
    })
}

/// Chip-specific specs resolved from `PCIe` device ID at runtime.
struct AkidaChipSpecs {
    name: &'static str,
    npu_count: usize,
    memory_bytes: usize,
}

impl AkidaChipSpecs {
    fn from_device_id(device_id: u16) -> Self {
        match device_id {
            0x1000 => Self {
                name: "Akida AKD1000",
                npu_count: 80,
                memory_bytes: 10 * 1024 * 1024,
            },
            0x1500 => Self {
                name: "Akida AKD1500",
                npu_count: 128,
                memory_bytes: 32 * 1024 * 1024,
            },
            _ => {
                tracing::warn!(
                    device_id,
                    "Unknown Akida device ID, using conservative defaults"
                );
                Self {
                    name: "Akida (unknown)",
                    npu_count: 1,
                    memory_bytes: 1024 * 1024,
                }
            }
        }
    }
}

/// `PCIe` device info
#[derive(Debug, Clone)]
struct PcieDevice {
    address: String,
    #[expect(dead_code, reason = "populated during PCIe scan, used for diagnostics")]
    vendor_id: u16,
    device_id: u16,
}

/// Scan `PCIe` bus for `BrainChip` Akida devices
fn scan_pcie_for_akida() -> Result<Vec<PcieDevice>> {
    // Scan /sys/bus/pci/devices for BrainChip vendor ID (0x1e7c)
    let pci_dir = "/sys/bus/pci/devices";

    let devices = if let Ok(entries) = std::fs::read_dir(pci_dir) {
        entries
            .flatten()
            .filter_map(|entry| {
                let path = entry.path();
                let address = entry.file_name().to_string_lossy().to_string();

                // Read vendor and device IDs
                let vendor_path = path.join("vendor");
                let device_path = path.join("device");

                let (vendor_str, device_str) = (
                    std::fs::read_to_string(&vendor_path),
                    std::fs::read_to_string(&device_path),
                );

                let (Ok(vendor_str), Ok(device_str)) = (vendor_str, device_str) else {
                    return None;
                };

                let Ok(vendor_id) =
                    u16::from_str_radix(vendor_str.trim().trim_start_matches("0x"), 16)
                else {
                    return None;
                };
                let Ok(device_id) =
                    u16::from_str_radix(device_str.trim().trim_start_matches("0x"), 16)
                else {
                    return None;
                };

                // BrainChip vendor ID is 0x1e7c
                // Akida AKD1000 device ID is 0x1000
                if vendor_id == 0x1e7c {
                    tracing::debug!(
                        "Found BrainChip device at {}: {:04x}:{:04x}",
                        address,
                        vendor_id,
                        device_id
                    );

                    Some(PcieDevice {
                        address,
                        vendor_id,
                        device_id,
                    })
                } else {
                    None
                }
            })
            .collect()
    } else {
        Vec::new()
    };

    Ok(devices)
}

/// Query board information
fn query_board_info(device: &PcieDevice, index: usize) -> Result<AkidaBoard> {
    let device_path = PathBuf::from(format!("/dev/akida{index}"));

    let (pcie_gen, pcie_lanes) = query_pcie_link_info(&device.address)?;

    // Query real power consumption from hwmon
    let power_watts = query_power_consumption(&device.address);

    // Query real temperature from hwmon
    let temperature_celsius = query_temperature(&device.address);

    let specs = AkidaChipSpecs::from_device_id(device.device_id);

    let board = AkidaBoard {
        index,
        pcie_address: device.address.clone(),
        device_path,
        chip_name: specs.name.to_string(),
        npu_count: specs.npu_count,
        memory_bytes: specs.memory_bytes,
        power_watts,
        temperature_celsius,
        pcie_generation: pcie_gen,
        pcie_lanes,
        health: check_board_health(&device.address)?,
    };

    Ok(board)
}

/// Query `PCIe` link status
fn query_pcie_link_info(address: &str) -> Result<(u8, u8)> {
    use std::fs;

    let base_path = format!("/sys/bus/pci/devices/{address}");

    // Read current link speed and width
    let speed_path = format!("{base_path}/current_link_speed");
    let width_path = format!("{base_path}/current_link_width");

    let generation = if let Ok(speed) = fs::read_to_string(&speed_path) {
        parse_pcie_speed(&speed)
    } else {
        2 // Default Gen2
    };

    let lanes = if let Ok(width) = fs::read_to_string(&width_path) {
        width.trim().parse().unwrap_or_else(|_| {
            tracing::debug!(address, "unparseable PCIe width, defaulting to x4");
            4
        })
    } else {
        4
    };

    Ok((generation, lanes))
}

/// Parse `PCIe` speed to generation
fn parse_pcie_speed(speed: &str) -> u8 {
    if speed.contains("2.5") {
        1 // Gen1: 2.5 GT/s
    } else if speed.contains("5.0") || speed.contains("5 GT") {
        2 // Gen2: 5.0 GT/s
    } else if speed.contains("8.0") || speed.contains("8 GT") {
        3 // Gen3: 8.0 GT/s
    } else if speed.contains("16.0") || speed.contains("16 GT") {
        4 // Gen4: 16.0 GT/s
    } else {
        2 // Default Gen2
    }
}

/// Query power consumption from hwmon
/// Deep Debt: Real hardware monitoring, no estimates!
fn query_power_consumption(pcie_address: &str) -> f64 {
    use std::fs;

    // Search for hwmon directory
    let hwmon_base = format!("/sys/bus/pci/devices/{pcie_address}/hwmon");

    if let Ok(entries) = fs::read_dir(&hwmon_base) {
        for entry in entries.flatten() {
            let hwmon_path = entry.path();
            let power_input_path = hwmon_path.join("power1_input");

            // power1_input is in microwatts
            if let Ok(power_str) = fs::read_to_string(&power_input_path)
                && let Ok(power_uw) = power_str.trim().parse::<f64>()
            {
                let power_watts = power_uw / 1_000_000.0; // Convert µW to W
                tracing::debug!(
                    "Akida {}: Measured power = {:.3}W",
                    pcie_address,
                    power_watts
                );
                return power_watts;
            }
        }
    }

    // Fallback: Use Akida AKD1000 typical power (0.5-2W range)
    // But log that we're using fallback
    tracing::warn!(
        "Akida {}: hwmon not available, using typical power estimate",
        pcie_address
    );
    1.0 // Typical idle power
}

/// Query temperature from hwmon
/// Deep Debt: Real hardware monitoring, no estimates!
fn query_temperature(pcie_address: &str) -> f64 {
    use std::fs;

    // Search for hwmon directory
    let hwmon_base = format!("/sys/bus/pci/devices/{pcie_address}/hwmon");

    if let Ok(entries) = fs::read_dir(&hwmon_base) {
        for entry in entries.flatten() {
            let hwmon_path = entry.path();
            let temp_input_path = hwmon_path.join("temp1_input");

            // temp1_input is in millidegrees celsius
            if let Ok(temp_str) = fs::read_to_string(&temp_input_path)
                && let Ok(temp_mdeg) = temp_str.trim().parse::<f64>()
            {
                let temp_celsius = temp_mdeg / 1000.0; // Convert millidegrees to degrees
                tracing::debug!(
                    "Akida {}: Measured temperature = {:.1}°C",
                    pcie_address,
                    temp_celsius
                );
                return temp_celsius;
            }
        }
    }

    // Fallback: Use Akida AKD1000 typical operating temperature
    // But log that we're using fallback
    tracing::warn!(
        "Akida {}: hwmon not available, using typical temperature estimate",
        pcie_address
    );
    40.0 // Typical operating temperature
}

/// Check board health
fn check_board_health(address: &str) -> Result<BoardHealth> {
    // Check if device is accessible
    let base_path = format!("/sys/bus/pci/devices/{address}");

    if std::fs::metadata(&base_path).is_ok() {
        // Device exists and is accessible
        Ok(BoardHealth::Healthy)
    } else {
        Ok(BoardHealth::Unknown)
    }
}

const AKIDA_SDK_SYSTEM_DIRS: &[&str] = &["/opt/akida", "/usr/local/akida", "/usr/share/akida"];

/// Detect Akida SDK version via capability-based discovery.
///
/// Resolution chain (first match wins):
/// 1. `AKIDA_HOME` environment variable → `$AKIDA_HOME/version`
/// 2. `AKIDA_SDK_DIR` environment variable → `$AKIDA_SDK_DIR/version`
/// 3. XDG data dirs → `$XDG_DATA_HOME/akida/version`
/// 4. System paths: `/opt/akida`, `/usr/local/akida`, `/usr/share/akida`
fn detect_akida_sdk_version() -> Option<String> {
    let mut search_paths = Vec::new();

    if let Ok(home) = std::env::var("AKIDA_HOME") {
        search_paths.push(format!("{home}/version"));
    }

    if let Ok(sdk_dir) = std::env::var("AKIDA_SDK_DIR") {
        search_paths.push(format!("{sdk_dir}/version"));
    }

    if let Ok(data_home) = std::env::var("XDG_DATA_HOME") {
        search_paths.push(format!("{data_home}/akida/version"));
    } else if let Ok(home) = std::env::var("HOME") {
        search_paths.push(format!("{home}/.local/share/akida/version"));
    }

    for dir in AKIDA_SDK_SYSTEM_DIRS {
        search_paths.push(format!("{dir}/version"));
    }

    for path in &search_paths {
        if let Ok(version) = std::fs::read_to_string(path) {
            return Some(version.trim().to_string());
        }
    }

    None
}

/// Model search directories for NPU model discovery.
///
/// Resolution chain (first match wins):
/// 1. `AKIDA_MODEL_PATH` environment variable
/// 2. `AKIDA_HOME` + `/models` if set
/// 3. `AKIDA_MODELS_DIR` environment variable (backward compat)
/// 4. XDG data dirs
/// 5. System paths: `/opt/akida/models`, `/usr/local/akida/models`, `/usr/share/akida/models`
pub(crate) fn akida_model_dirs() -> Vec<std::path::PathBuf> {
    let mut dirs = Vec::new();

    if let Ok(path) = std::env::var("AKIDA_MODEL_PATH") {
        dirs.push(std::path::PathBuf::from(path));
    }

    if let Ok(home) = std::env::var("AKIDA_HOME") {
        dirs.push(std::path::PathBuf::from(home).join("models"));
    }

    if let Ok(dir) = std::env::var("AKIDA_MODELS_DIR") {
        dirs.push(std::path::PathBuf::from(dir));
    }

    if let Ok(data_home) = std::env::var("XDG_DATA_HOME") {
        dirs.push(std::path::PathBuf::from(data_home).join("akida/models"));
    } else if let Ok(home) = std::env::var("HOME") {
        dirs.push(std::path::PathBuf::from(home).join(".local/share/akida/models"));
    }

    for dir in AKIDA_SDK_SYSTEM_DIRS {
        dirs.push(std::path::PathBuf::from(dir).join("models"));
    }

    dirs
}

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

    #[test]
    fn test_akida_detection() {
        let _caps =
            detect_akida_boards().expect("detect_akida_boards should succeed on any system");
    }
}