1use serde::{Deserialize, Serialize};
9use std::fs;
10use std::path::Path;
11
12#[cfg(not(target_arch = "wasm32"))]
14fn get_hostname() -> String {
15 hostname::get().map(|h| h.to_string_lossy().to_string()).unwrap_or_else(|e| {
16 eprintln!("warning: failed to get hostname: {e}");
17 "unknown".to_string()
18 })
19}
20
21#[cfg(target_arch = "wasm32")]
23fn get_hostname() -> String {
24 "wasm".to_string()
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
29pub enum SimdWidth {
30 Scalar,
32 Neon128,
34 Sse2,
36 Avx2,
38 Avx512,
40 WasmSimd128,
42}
43
44impl SimdWidth {
45 pub fn lanes(&self) -> usize {
47 match self {
48 SimdWidth::Scalar => 1,
49 SimdWidth::Neon128 | SimdWidth::Sse2 | SimdWidth::WasmSimd128 => 4,
50 SimdWidth::Avx2 => 8,
51 SimdWidth::Avx512 => 16,
52 }
53 }
54
55 pub fn bits(&self) -> usize {
57 self.lanes() * 32
58 }
59
60 pub fn compute_speedup(&self) -> f64 {
62 match self {
63 SimdWidth::Scalar => 1.0,
64 SimdWidth::Neon128 | SimdWidth::Sse2 | SimdWidth::WasmSimd128 => 4.0,
65 SimdWidth::Avx2 => 10.0, SimdWidth::Avx512 => 12.0, }
68 }
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73pub enum GpuBackend {
74 None,
76 Cuda,
78 Wgpu,
80 Metal,
82 Vulkan,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct CpuCapability {
89 pub vendor: String,
91 pub model: String,
93 pub cores: usize,
95 pub threads: usize,
97 pub simd: SimdWidth,
99 pub base_freq_ghz: f64,
101 pub peak_gflops: f64,
103 pub memory_bw_gbps: f64,
105}
106
107#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct GpuCapability {
110 pub vendor: String,
112 pub model: String,
114 pub backend: GpuBackend,
116 pub compute_capability: Option<String>,
118 pub peak_tflops_fp32: f64,
120 pub peak_tflops_tensor: Option<f64>,
122 pub memory_bw_gbps: f64,
124 pub vram_gb: f64,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct HardwareCapability {
131 pub timestamp: String,
133 pub hostname: String,
135 pub cpu: CpuCapability,
137 pub gpu: Option<GpuCapability>,
139 pub roofline: RooflineParams,
141 #[serde(default)]
143 pub byte_budget: Option<crate::brick::ByteBudget>,
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct RooflineParams {
149 pub cpu_arithmetic_intensity: f64,
151 pub gpu_arithmetic_intensity: Option<f64>,
153}
154
155fn format_rfc3339_utc(secs: i64, nanos: u32) -> String {
159 let days = secs.div_euclid(86_400);
160 let tod = secs.rem_euclid(86_400);
161 let z = days + 719_468;
163 let era = z.div_euclid(146_097);
164 let doe = z.rem_euclid(146_097);
165 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
166 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
167 let mp = (5 * doy + 2) / 153;
168 let d = doy - (153 * mp + 2) / 5 + 1;
169 let m = if mp < 10 { mp + 3 } else { mp - 9 };
170 let y = yoe + era * 400 + i64::from(m <= 2);
171 let frac = if nanos == 0 {
172 String::new()
173 } else if nanos % 1_000_000 == 0 {
174 format!(".{:03}", nanos / 1_000_000)
175 } else if nanos % 1_000 == 0 {
176 format!(".{:06}", nanos / 1_000)
177 } else {
178 format!(".{nanos:09}")
179 };
180 format!(
181 "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}{frac}+00:00",
182 tod / 3_600,
183 tod % 3_600 / 60,
184 tod % 60
185 )
186}
187
188fn now_rfc3339() -> String {
190 let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
191 format_rfc3339_utc(d.as_secs() as i64, d.subsec_nanos())
192}
193
194impl HardwareCapability {
195 pub fn detect() -> Self {
197 let cpu = detect_cpu();
198 let gpu = detect_gpu();
199
200 let cpu_ai = cpu.peak_gflops / cpu.memory_bw_gbps;
201 let gpu_ai = gpu.as_ref().map(|g| g.peak_tflops_fp32 * 1000.0 / g.memory_bw_gbps);
202 let byte_budget_throughput = cpu.memory_bw_gbps.min(25.0);
204
205 HardwareCapability {
206 timestamp: now_rfc3339(),
207 hostname: get_hostname(),
208 cpu,
209 gpu,
210 roofline: RooflineParams {
211 cpu_arithmetic_intensity: cpu_ai,
212 gpu_arithmetic_intensity: gpu_ai,
213 },
214 byte_budget: Some(crate::brick::ByteBudget::from_throughput(byte_budget_throughput)),
216 }
217 }
218
219 pub fn load_or_detect(path: &Path) -> Self {
221 if path.exists() {
222 if let Ok(content) = fs::read_to_string(path) {
223 if let Ok(cap) = toml::from_str(&content) {
224 return cap;
225 }
226 }
227 }
228 let cap = Self::detect();
229 let _ = cap.save(path);
231 cap
232 }
233
234 pub fn save(&self, path: &Path) -> std::io::Result<()> {
236 if let Some(parent) = path.parent() {
237 fs::create_dir_all(parent)?;
238 }
239 let content = toml::to_string_pretty(self)
240 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
241 fs::write(path, content)
242 }
243
244 pub fn best_backend(&self) -> GpuBackend {
246 self.gpu.as_ref().map(|g| g.backend).unwrap_or(GpuBackend::None)
247 }
248
249 pub fn expected_throughput_gflops(&self, arithmetic_intensity: f64, use_gpu: bool) -> f64 {
251 if use_gpu {
252 if let Some(gpu) = &self.gpu {
253 let memory_bound = gpu.memory_bw_gbps * arithmetic_intensity;
254 let compute_bound = gpu.peak_tflops_fp32 * 1000.0;
255 memory_bound.min(compute_bound)
256 } else {
257 self.cpu_expected_throughput(arithmetic_intensity)
258 }
259 } else {
260 self.cpu_expected_throughput(arithmetic_intensity)
261 }
262 }
263
264 fn cpu_expected_throughput(&self, arithmetic_intensity: f64) -> f64 {
265 let memory_bound = self.cpu.memory_bw_gbps * arithmetic_intensity;
266 let compute_bound = self.cpu.peak_gflops;
267 memory_bound.min(compute_bound)
268 }
269
270 pub fn bottleneck(&self, arithmetic_intensity: f64, use_gpu: bool) -> Bottleneck {
272 let threshold = if use_gpu {
273 self.roofline.gpu_arithmetic_intensity.unwrap_or(f64::MAX)
274 } else {
275 self.roofline.cpu_arithmetic_intensity
276 };
277
278 if arithmetic_intensity < threshold {
279 Bottleneck::Memory
280 } else {
281 Bottleneck::Compute
282 }
283 }
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
288pub enum Bottleneck {
289 Memory,
291 Compute,
293}
294
295fn normalize_cpu_vendor(raw: &str) -> String {
297 match raw.trim() {
298 "GenuineIntel" => "Intel".to_string(),
299 "AuthenticAMD" => "AMD".to_string(),
300 "" => "Unknown".to_string(),
301 other => other.to_string(),
302 }
303}
304
305pub fn parse_cpuinfo(contents: &str) -> (Option<String>, Option<String>) {
316 let mut vendor = None;
317 let mut model = None;
318 for line in contents.lines() {
319 let Some((key, value)) = line.split_once(':') else {
320 continue;
321 };
322 let key = key.trim();
323 let value = value.trim();
324 if value.is_empty() {
325 continue;
326 }
327 match key {
328 "vendor_id" if vendor.is_none() => vendor = Some(normalize_cpu_vendor(value)),
329 "model name" | "Model" if model.is_none() => model = Some(value.to_string()),
330 "CPU implementer" if vendor.is_none() => {
332 vendor = Some(match value {
333 "0x41" => "ARM".to_string(),
334 "0x51" => "Qualcomm".to_string(),
335 "0x4e" => "NVIDIA".to_string(),
336 other => other.to_string(),
337 });
338 }
339 _ => {}
340 }
341 }
342 (vendor, model)
343}
344
345fn detect_cpu_identity() -> (String, String) {
347 #[cfg(target_os = "linux")]
348 {
349 if let Ok(contents) = fs::read_to_string("/proc/cpuinfo") {
350 let (vendor, model) = parse_cpuinfo(&contents);
351 return (
352 vendor.unwrap_or_else(|| "Unknown".to_string()),
353 model.unwrap_or_else(|| "Unknown".to_string()),
354 );
355 }
356 }
357 ("Unknown".to_string(), "Unknown".to_string())
358}
359
360fn detect_cpu() -> CpuCapability {
362 let simd = detect_simd();
363 let cores = num_cpus::get_physical();
364 let threads = num_cpus::get();
365 let (vendor, model) = detect_cpu_identity();
366
367 let base_freq_ghz = 3.0;
369
370 let peak_gflops = (cores as f64) * (simd.lanes() as f64) * 2.0 * base_freq_ghz;
372
373 let memory_bw_gbps = 80.0; CpuCapability {
377 vendor,
378 model,
379 cores,
380 threads,
381 simd,
382 base_freq_ghz,
383 peak_gflops,
384 memory_bw_gbps,
385 }
386}
387
388fn detect_simd() -> SimdWidth {
390 #[cfg(target_arch = "x86_64")]
391 {
392 if is_x86_feature_detected!("avx512f") {
393 return SimdWidth::Avx512;
394 }
395 if is_x86_feature_detected!("avx2") {
396 return SimdWidth::Avx2;
397 }
398 if is_x86_feature_detected!("sse2") {
399 return SimdWidth::Sse2;
400 }
401 }
402
403 #[cfg(target_arch = "aarch64")]
404 {
405 SimdWidth::Neon128
407 }
408
409 #[cfg(target_arch = "wasm32")]
410 {
411 SimdWidth::WasmSimd128
412 }
413
414 #[cfg(not(any(target_arch = "aarch64", target_arch = "wasm32")))]
415 {
416 SimdWidth::Scalar
417 }
418}
419
420fn detect_gpu() -> Option<GpuCapability> {
422 #[cfg(feature = "cuda")]
424 {
425 if let Some(gpu) = detect_cuda_gpu() {
426 return Some(gpu);
427 }
428 }
429
430 None
432}
433
434#[cfg(feature = "cuda")]
435fn detect_cuda_gpu() -> Option<GpuCapability> {
436 None
439}
440
441pub fn default_hardware_path() -> std::path::PathBuf {
443 #[cfg(feature = "hardware-detect")]
444 {
445 dirs::home_dir()
446 .unwrap_or_else(|| std::path::PathBuf::from("."))
447 .join(".pmat")
448 .join("hardware.toml")
449 }
450 #[cfg(not(feature = "hardware-detect"))]
451 {
452 std::path::PathBuf::from(".pmat").join("hardware.toml")
453 }
454}
455
456#[cfg(test)]
457mod tests;