Skip to main content

weirdnet_model/
cpu.rs

1//! Can this CPU run the llama.cpp compiled into this build?
2//!
3//! llama.cpp's build turns on AVX, AVX2, BMI2, FMA and F16C by default. A static build made that
4//! way dies with an illegal instruction on x86 CPUs without them (most made before 2013) the first
5//! time ggml runs. [`check`] compares what the build contains (worked out by `build.rs`) with what
6//! this CPU has, and [`LlamaEngine::load`](crate::llama::LlamaEngine) calls it before any llama.cpp
7//! code runs, so such a CPU gets [`Error::UnsupportedCpu`] instead of a crash.
8//!
9//! With the `cpu-dispatch` feature ggml is built for every CPU level and picks the best one at run
10//! time, so nothing is required and [`check`] always passes. ARM builds use the target's baseline
11//! (armv8-a on Linux, the Apple M1 level on macOS), which every CPU of that target has.
12
13use crate::{Error, Result};
14
15/// x86 instructions this build's llama.cpp contains (`is_x86_feature_detected!` names). Empty
16/// without the `llama` feature, with `cpu-dispatch`, and on non-x86 targets.
17pub fn required() -> Vec<&'static str> {
18    env!("WEIRDNET_MODEL_GGML_X86").split(',').filter(|s| !s.is_empty()).collect()
19}
20
21/// The [`required`] instructions this CPU lacks (empty when local inference can run).
22pub fn missing() -> Vec<&'static str> {
23    missing_from(&required(), has)
24}
25
26/// `Ok` when this CPU can run the compiled-in llama.cpp, else [`Error::UnsupportedCpu`]. Cheap
27/// (the detection is cached), so apps can call it to decide whether to offer local models.
28pub fn check() -> Result<()> {
29    let missing = missing();
30    if missing.is_empty() { Ok(()) } else { Err(Error::UnsupportedCpu { missing: missing.into_iter().map(String::from).collect() }) }
31}
32
33fn missing_from<'a>(required: &[&'a str], has: impl Fn(&str) -> bool) -> Vec<&'a str> {
34    required.iter().copied().filter(|f| !has(f)).collect()
35}
36
37/// Whether this CPU (and OS, for the AVX register state) supports `feature`. Unknown names count
38/// as missing.
39#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
40fn has(feature: &str) -> bool {
41    match feature {
42        "sse4.2" => std::is_x86_feature_detected!("sse4.2"),
43        "avx" => std::is_x86_feature_detected!("avx"),
44        "avx2" => std::is_x86_feature_detected!("avx2"),
45        "bmi2" => std::is_x86_feature_detected!("bmi2"),
46        "fma" => std::is_x86_feature_detected!("fma"),
47        "f16c" => std::is_x86_feature_detected!("f16c"),
48        "avxvnni" => std::is_x86_feature_detected!("avxvnni"),
49        "avx512f" => std::is_x86_feature_detected!("avx512f"),
50        "avx512cd" => std::is_x86_feature_detected!("avx512cd"),
51        "avx512vl" => std::is_x86_feature_detected!("avx512vl"),
52        "avx512dq" => std::is_x86_feature_detected!("avx512dq"),
53        "avx512bw" => std::is_x86_feature_detected!("avx512bw"),
54        "avx512vbmi" => std::is_x86_feature_detected!("avx512vbmi"),
55        "avx512vnni" => std::is_x86_feature_detected!("avx512vnni"),
56        "avx512bf16" => std::is_x86_feature_detected!("avx512bf16"),
57        _ => false,
58    }
59}
60
61#[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))]
62fn has(_feature: &str) -> bool {
63    false
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69
70    /// What llama.cpp's default x86 build needs.
71    const DEFAULT_BUILD: &[&str] = &["avx", "avx2", "bmi2", "f16c", "fma", "sse4.2"];
72
73    #[test]
74    fn a_nehalem_lacks_what_the_default_build_needs() {
75        let nehalem = |f: &str| f == "sse4.2";
76        assert_eq!(missing_from(DEFAULT_BUILD, nehalem), ["avx", "avx2", "bmi2", "f16c", "fma"]);
77        let sandy_bridge = |f: &str| matches!(f, "sse4.2" | "avx");
78        assert_eq!(missing_from(DEFAULT_BUILD, sandy_bridge), ["avx2", "bmi2", "f16c", "fma"]);
79    }
80
81    #[test]
82    fn a_haswell_has_everything_the_default_build_needs() {
83        let haswell = |f: &str| matches!(f, "sse4.2" | "avx" | "avx2" | "bmi2" | "fma" | "f16c");
84        assert!(missing_from(DEFAULT_BUILD, haswell).is_empty());
85    }
86
87    #[test]
88    fn unsupported_cpu_names_the_missing_instructions() {
89        let e = Error::UnsupportedCpu { missing: vec!["avx2".into(), "fma".into()] };
90        let s = e.to_string();
91        assert!(s.contains("avx2, fma"), "{s}");
92    }
93
94    #[test]
95    fn the_build_machine_can_run_its_own_build() {
96        // Tests run where they were built, so a mismatch here is a build.rs bug.
97        assert_eq!(missing(), Vec::<&str>::new(), "required {:?}", required());
98        check().unwrap();
99    }
100
101    #[test]
102    fn the_requirement_matches_the_features() {
103        let r = required();
104        if !cfg!(feature = "llama") || cfg!(feature = "cpu-dispatch") || !cfg!(any(target_arch = "x86_64", target_arch = "x86")) {
105            assert!(r.is_empty(), "{r:?}");
106        }
107        for f in &r {
108            assert!(!f.is_empty() && !f.contains(','), "{r:?}");
109        }
110    }
111}