diff --git a/crates/cuda-driver/src/gpu_report.rs b/crates/cuda-driver/src/gpu_report.rs new file mode 100644 index 00000000..21b5c87a --- /dev/null +++ b/crates/cuda-driver/src/gpu_report.rs @@ -0,0 +1,150 @@ +//! Start-up report of the CUDA devices and of the kernel set each one runs (operator log only, no behaviour). +//! +//! Every PTX asset of this crate is sealed for sm_120. A device of compute capability 12.x loads those images as they are; a device of +//! 8.6 <= cc < 12.0 loads the pinned sm_86 companions when the build has the `sm86` feature (`arch_ptx`); anything else cannot load them. +//! The report goes through the driver API directly (no context needed), so it lists every device of the machine, not only the one in use. +#![allow(unsafe_code)] + +/// One line per CUDA device, preceded by one line with the driver version. Empty when the driver cannot be loaded. +pub fn gpu_kernel_report() -> Vec { + imp::report() +} + +/// The kernel set a device of compute capability (`major`, `minor`) runs, and the MMQ launch policy that follows from it. +fn kernel_set(major: i32, minor: i32, sm86_build: bool) -> (&'static str, &'static str) { + if major >= 12 { + ("sealed sm_120 PTX, native", "stream-K grid") + } else if (major, minor) >= (8, 6) { + if sm86_build { + ("pinned sm_86 companion PTX of the sealed sm_120 images", "one block per tile (stream-K off, STRA-235)") + } else { + ("NONE: this build has no sm_86 companions, the sealed sm_120 images cannot load", "-") + } + } else { + ("NONE: compute capability below 8.6 is not supported", "-") + } +} + +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +mod imp { + use super::kernel_set; + use std::ffi::{CStr, c_char, c_int, c_void}; + + type Init = unsafe extern "C" fn(u32) -> c_int; + type Count = unsafe extern "C" fn(*mut c_int) -> c_int; + type Get = unsafe extern "C" fn(*mut c_int, c_int) -> c_int; + type Name = unsafe extern "C" fn(*mut c_char, c_int, c_int) -> c_int; + type TotalMem = unsafe extern "C" fn(*mut usize, c_int) -> c_int; + type Attr = unsafe extern "C" fn(*mut c_int, c_int, c_int) -> c_int; + type Version = unsafe extern "C" fn(*mut c_int) -> c_int; + + /// # Safety + /// `T` must be the exact `extern "C"` signature of the named driver function. + unsafe fn symbol(handle: *mut c_void, name: &CStr) -> Option { + debug_assert_eq!(std::mem::size_of::(), std::mem::size_of::<*mut c_void>()); + // SAFETY: valid dlopen handle and a static C name. + let address = unsafe { libc::dlsym(handle, name.as_ptr()) }; + if address.is_null() { + None + } else { + // SAFETY: function pointers and data pointers have the same size on the 64-bit targets; signature per the caller. + Some(unsafe { std::mem::transmute_copy::<*mut c_void, T>(&address) }) + } + } + + pub(super) fn report() -> Vec { + // SAFETY: fixed library name; the handle is closed below. + let handle = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW) }; + if handle.is_null() { + return Vec::new(); + } + let lines = (|| { + // SAFETY: fixed driver symbol names, paired with their documented signatures. + let (init, count, get, name, total, attr, version) = unsafe { + ( + symbol::(handle, c"cuInit")?, + symbol::(handle, c"cuDeviceGetCount")?, + symbol::(handle, c"cuDeviceGet")?, + symbol::(handle, c"cuDeviceGetName")?, + symbol::(handle, c"cuDeviceTotalMem_v2")?, + symbol::(handle, c"cuDeviceGetAttribute")?, + symbol::(handle, c"cuDriverGetVersion")?, + ) + }; + let sm86_build = cfg!(feature = "sm86"); + let mut lines = Vec::new(); + let (mut n, mut v) = (0, 0); + // SAFETY: valid writable outputs for every driver call below; devices are queried by ordinals the driver just counted. + unsafe { + if init(0) != 0 || count(&mut n) != 0 { + return None; + } + let _ = version(&mut v); + lines.push(format!( + "gpu: CUDA driver {}.{}, {n} device(s), sm_86 companions in this build: {}, chain kernels: {}", + v / 1000, + v % 1000 / 10, + if sm86_build { "yes" } else { "no" }, + std::env::var("LELEKA_CHAIN").unwrap_or_else(|_| "default".to_owned()) + )); + for ordinal in 0..n { + let mut dev = 0; + if get(&mut dev, ordinal) != 0 { + continue; + } + let mut label = [0 as c_char; 128]; + let label = if name(label.as_mut_ptr(), 128, dev) == 0 { + CStr::from_ptr(label.as_ptr()).to_string_lossy().into_owned() + } else { + "unknown model".to_owned() + }; + let (mut major, mut minor, mut sms, mut bytes) = (0, 0, 0, 0usize); + let _ = attr(&mut major, 75, dev); + let _ = attr(&mut minor, 76, dev); + let _ = attr(&mut sms, 16, dev); + let _ = total(&mut bytes, dev); + let (set, mmq) = kernel_set(major, minor, sm86_build); + lines.push(format!( + "gpu {ordinal}: {label}, cc {major}.{minor}, {sms} SMs, {:.1} GiB; kernels: {set}; MMQ launch: {mmq}", + bytes as f64 / f64::from(1u32 << 30) + )); + } + } + Some(lines) + })(); + // SAFETY: the handle returned above, closed exactly once. + unsafe { + libc::dlclose(handle); + } + lines.unwrap_or_default() + } +} + +#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64")))] +mod imp { + pub(super) fn report() -> Vec { + Vec::new() + } +} + +#[cfg(test)] +mod tests { + use super::kernel_set; + + #[test] + fn the_kernel_set_follows_the_compute_capability() { + assert_eq!(kernel_set(12, 0, false).0, "sealed sm_120 PTX, native"); + assert!(kernel_set(8, 6, true).0.contains("sm_86 companion")); + assert!(kernel_set(8, 9, true).0.contains("sm_86 companion")); + assert!(kernel_set(8, 6, false).0.starts_with("NONE")); + assert!(kernel_set(7, 5, true).0.starts_with("NONE")); + } + + #[test] + fn the_report_never_panics_without_a_driver() { + for line in super::gpu_kernel_report() { + eprintln!("{line}"); + assert!(line.starts_with("gpu")); + } + } +} diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index cfc4b6ce..0e136ac9 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -3233,6 +3233,8 @@ mod original_sampler_params; mod sealed_ptx; #[allow(unsafe_code)] mod arch_ptx; +mod gpu_report; +pub use gpu_report::gpu_kernel_report; #[cfg(feature = "sm86")] mod sm86_table; #[allow(unsafe_code)] diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 5a8adeb7..6ed24938 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -484,6 +484,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { }; let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; let residency = ResidencyState::new(&config.expert_tier); + report_kernel_selection(); vram_note(context, "before expert tier"); let mut loan = None; let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); @@ -1567,6 +1568,17 @@ pub(crate) fn dbg_el() -> f32 { DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32() } +/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only). +fn report_kernel_selection() { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + for line in leleka_native_cpu_expert::cpu_kernel_report() { + operator_note(&line); + } + for line in leleka_cuda_driver::gpu_kernel_report() { + operator_note(&line); + } +} + fn operator_note(text: &str) { use std::io::Write; let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}"); diff --git a/crates/native-cpu-expert/src/cpu_report.rs b/crates/native-cpu-expert/src/cpu_report.rs new file mode 100644 index 00000000..d33b7a7b --- /dev/null +++ b/crates/native-cpu-expert/src/cpu_report.rs @@ -0,0 +1,147 @@ +//! Start-up report of the CPUs the expert kernels run on and of the kernel family chosen for them (operator log only, no behaviour). +//! +//! The kernel family (AVX-512 or AVX2) is decided once per process by `rust_simd::dispatch()`. This report probes every logical CPU the +//! process may run on (a thread pinned to it, `cpuid`, `xgetbv`) and groups the identical ones, so a machine with several packages or +//! with unlike cores shows each kind on its own line, and a core that cannot run the chosen family is named. +use core::arch::x86_64::{__cpuid, __cpuid_count, _xgetbv}; + +#[derive(Clone, PartialEq, Eq)] +struct Core { + brand: String, + avx2: bool, + avx512: [bool; 6], +} + +const AVX512_NAMES: [&str; 6] = ["F", "BW", "VL", "DQ", "VBMI", "VNNI"]; + +/// The features of the core the calling thread runs on. The gates mirror `rust_simd::probe_avx2` / `probe_avx512`. +fn probe() -> Core { + // SAFETY: CPUID is always available on x86_64; XGETBV only after the OSXSAVE bit is seen. + unsafe { + let max = __cpuid(0).eax; + let ext = __cpuid(0x8000_0000).eax; + let mut brand = String::new(); + if ext >= 0x8000_0004 { + let mut raw = Vec::with_capacity(48); + for leaf in 0x8000_0002..=0x8000_0004u32 { + let r = __cpuid(leaf); + for w in [r.eax, r.ebx, r.ecx, r.edx] { + raw.extend_from_slice(&w.to_le_bytes()); + } + } + brand = String::from_utf8_lossy(&raw).trim_matches(|c: char| c == '\0' || c.is_whitespace()).to_owned(); + } + if max < 7 { + return Core { brand, avx2: false, avx512: [false; 6] }; + } + let c1 = __cpuid(1).ecx; + let osxsave = c1 & (1 << 27) != 0; + let xcr0 = if osxsave { _xgetbv(0) } else { 0 }; + let l7 = __cpuid_count(7, 0); + let avx2 = [12, 27, 28, 29].iter().all(|b| c1 & (1 << b) != 0) && xcr0 & 6 == 6 && l7.ebx & (1 << 5) != 0; + let os512 = osxsave && xcr0 & 0xe6 == 0xe6; + let bits = [l7.ebx & (1 << 16) != 0, l7.ebx & (1 << 30) != 0, l7.ebx & (1 << 31) != 0, l7.ebx & (1 << 17) != 0, l7.ecx & (1 << 1) != 0, l7.ecx & (1 << 11) != 0]; + Core { brand, avx2, avx512: bits.map(|b| b && os512) } + } +} + +fn avx512_complete(c: &Core) -> bool { + c.avx512.iter().all(|b| *b) +} + +/// `0-7,12` style list of CPU indexes. +fn ranges(cpus: &[usize]) -> String { + let mut out = String::new(); + let mut i = 0; + while i < cpus.len() { + let mut j = i; + while j + 1 < cpus.len() && cpus[j + 1] == cpus[j] + 1 { + j += 1; + } + if !out.is_empty() { + out.push(','); + } + out.push_str(&if i == j { cpus[i].to_string() } else { format!("{}-{}", cpus[i], cpus[j]) }); + i = j + 1; + } + out +} + +/// One line per kind of logical CPU, then one line with the kernel family the process chose and the switches that changed it. +pub fn cpu_kernel_report() -> Vec { + let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256); + let mut groups: Vec<(Core, Vec)> = Vec::new(); + for cpu in 0..n { + // a pinned probe thread per logical CPU; a refused pin probes wherever the thread runs (the line then shows that CPU's kind) + let core = std::thread::spawn(move || { + let previous = crate::rust_topology::pin_current_thread(cpu as i32); + let core = probe(); + crate::rust_topology::restore_thread_affinity(previous); + core + }) + .join(); + let Ok(core) = core else { continue }; + match groups.iter_mut().find(|(g, _)| *g == core) { + Some((_, cpus)) => cpus.push(cpu), + None => groups.push((core, vec![cpu])), + } + } + let mut lines = Vec::new(); + for (core, cpus) in &groups { + let have: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| *b).map(|(n, _)| *n).collect(); + let lacks: Vec<&str> = AVX512_NAMES.iter().zip(core.avx512).filter(|(_, b)| !*b).map(|(n, _)| *n).collect(); + let avx512 = if lacks.is_empty() { + "AVX-512 F/BW/VL/DQ/VBMI/VNNI: all".to_owned() + } else if have.is_empty() { + "AVX-512: none".to_owned() + } else { + format!("AVX-512: has {}, lacks {}", have.join("/"), lacks.join("/")) + }; + lines.push(format!( + "cpu: logical {} ({}): {}; AVX2/FMA/F16C: {}; {}; kernel family on this core: {}", + ranges(cpus), + cpus.len(), + if core.brand.is_empty() { "unknown model" } else { &core.brand }, + if core.avx2 { "yes" } else { "no" }, + avx512, + if avx512_complete(core) { "AVX-512" } else if core.avx2 { "AVX2" } else { "none (unsupported)" } + )); + } + let dispatch = crate::rust_simd::dispatch(); + let mut switches = Vec::new(); + for name in ["STRATA_FORCE_AVX2", "STRATA_NO_IQ512", "STRATA_NO_IQ256", "STRATA_NO_IQ4NL"] { + if std::env::var_os(name).is_some() { + switches.push(name); + } + } + lines.push(format!( + "cpu: process kernel family {} (IQ rows: 512-bit {}, 256-bit {}; IQ4_NL {}){}", + if dispatch.avx512 { "AVX-512" } else { "AVX2" }, + if dispatch.iq512 { "on" } else { "off" }, + if dispatch.iq256 { "on" } else { "off" }, + if dispatch.iq4nl { "on" } else { "off" }, + if switches.is_empty() { String::new() } else { format!("; overridden by {}", switches.join(", ")) } + )); + if groups.len() > 1 && groups.iter().any(|(c, _)| avx512_complete(c) != dispatch.avx512 && (dispatch.avx512 || avx512_complete(c))) { + lines.push("cpu: WARNING: the logical CPUs differ in AVX-512 support but the kernel family is chosen once per process; a worker pinned to a core without it would fault or be refused".to_owned()); + } + lines +} + +#[cfg(test)] +mod tests { + #[test] + fn the_report_names_every_logical_cpu_once_and_the_process_family() { + let lines = super::cpu_kernel_report(); + eprintln!("{}", lines.join("\n")); + assert!(lines.iter().any(|l| l.starts_with("cpu: logical "))); + assert!(lines.iter().any(|l| l.starts_with("cpu: process kernel family "))); + let n = std::thread::available_parallelism().map_or(1, |n| n.get()).min(256); + let counted: usize = lines + .iter() + .filter(|l| l.starts_with("cpu: logical ")) + .map(|l| l.split(['(', ')']).nth(1).and_then(|c| c.parse::().ok()).unwrap_or(0)) + .sum(); + assert_eq!(counted, n, "every probed logical CPU is in exactly one group"); + } +} diff --git a/crates/native-cpu-expert/src/lib.rs b/crates/native-cpu-expert/src/lib.rs index ee4183fe..1007a8df 100644 --- a/crates/native-cpu-expert/src/lib.rs +++ b/crates/native-cpu-expert/src/lib.rs @@ -8,6 +8,9 @@ mod rust_types; #[allow(unsafe_code)] mod rust_simd; #[allow(unsafe_code)] +mod cpu_report; +pub use cpu_report::cpu_kernel_report; +#[allow(unsafe_code)] mod rust_quant; #[allow(unsafe_code)] mod rust_iq;