use crate::error::Result;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct AkidaBoard {
pub index: usize,
pub pcie_address: String,
pub device_path: PathBuf,
pub chip_name: String,
pub npu_count: usize,
pub memory_bytes: usize,
pub power_watts: f64,
pub temperature_celsius: f64,
pub pcie_generation: u8,
pub pcie_lanes: u8,
pub health: BoardHealth,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardHealth {
Healthy,
Warning,
Critical,
Unknown,
}
#[derive(Debug, Clone)]
pub struct AkidaCapabilities {
pub boards: Vec<AkidaBoard>,
pub total_npus: usize,
pub total_memory_bytes: usize,
pub sdk_version: Option<String>,
}
pub fn detect_akida_boards() -> Result<AkidaCapabilities> {
tracing::info!("Detecting Akida NPU boards...");
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());
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();
let total_npus = boards.iter().map(|b| b.npu_count).sum();
let total_memory_bytes = boards.iter().map(|b| b.memory_bytes).sum();
let sdk_version = detect_akida_sdk_version();
Ok(AkidaCapabilities {
boards,
total_npus,
total_memory_bytes,
sdk_version,
})
}
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,
}
}
}
}
}
#[derive(Debug, Clone)]
struct PcieDevice {
address: String,
#[expect(dead_code, reason = "populated during PCIe scan, used for diagnostics")]
vendor_id: u16,
device_id: u16,
}
fn scan_pcie_for_akida() -> Result<Vec<PcieDevice>> {
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();
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;
};
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)
}
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)?;
let power_watts = query_power_consumption(&device.address);
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)
}
fn query_pcie_link_info(address: &str) -> Result<(u8, u8)> {
use std::fs;
let base_path = format!("/sys/bus/pci/devices/{address}");
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 };
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))
}
fn parse_pcie_speed(speed: &str) -> u8 {
if speed.contains("2.5") {
1 } else if speed.contains("5.0") || speed.contains("5 GT") {
2 } else if speed.contains("8.0") || speed.contains("8 GT") {
3 } else if speed.contains("16.0") || speed.contains("16 GT") {
4 } else {
2 }
}
fn query_power_consumption(pcie_address: &str) -> f64 {
use std::fs;
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");
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; tracing::debug!(
"Akida {}: Measured power = {:.3}W",
pcie_address,
power_watts
);
return power_watts;
}
}
}
tracing::warn!(
"Akida {}: hwmon not available, using typical power estimate",
pcie_address
);
1.0 }
fn query_temperature(pcie_address: &str) -> f64 {
use std::fs;
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");
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; tracing::debug!(
"Akida {}: Measured temperature = {:.1}°C",
pcie_address,
temp_celsius
);
return temp_celsius;
}
}
}
tracing::warn!(
"Akida {}: hwmon not available, using typical temperature estimate",
pcie_address
);
40.0 }
fn check_board_health(address: &str) -> Result<BoardHealth> {
let base_path = format!("/sys/bus/pci/devices/{address}");
if std::fs::metadata(&base_path).is_ok() {
Ok(BoardHealth::Healthy)
} else {
Ok(BoardHealth::Unknown)
}
}
const AKIDA_SDK_SYSTEM_DIRS: &[&str] = &["/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
}
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");
}
}