Skip to main content

kodamaembed_cpu/
lib.rs

1//! CPU backend for KodamaEmbed: FP32 by default, an opt-in INT8 preset
2//! ([`CpuPrecision`]), and every output independent of its batch.
3
4#![doc(
5    html_logo_url = "https://raw.githubusercontent.com/yp3y5akh0v/kodamaembed/master/docs/assets/crest.svg",
6    html_favicon_url = "https://raw.githubusercontent.com/yp3y5akh0v/kodamaembed/master/docs/assets/favicon.ico"
7)]
8
9mod attention;
10mod encoder;
11mod gemm;
12#[cfg(target_arch = "x86_64")]
13mod int8;
14mod math;
15mod precision;
16mod projection;
17mod workers;
18
19pub use attention::attention;
20#[doc(hidden)]
21#[cfg(target_arch = "x86_64")]
22pub use attention::integer_attention;
23#[doc(hidden)]
24pub use encoder::pool_rows;
25pub use encoder::{Encoder, EncoderError, TokenSequence};
26pub use gemm::{Epilogue, Kernel, PackedWeight, gemm};
27pub use precision::CpuPrecision;
28pub use workers::{Workers, worker_pool};
29
30/// Equal lengths divisible by eight; needs AVX2 and FMA.
31#[doc(hidden)]
32#[cfg(target_arch = "x86_64")]
33pub fn gelus(x: &[f32], out: &mut [f32]) {
34    use std::arch::x86_64::{_mm256_loadu_ps, _mm256_storeu_ps};
35    assert!(is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma"));
36    assert!(
37        x.len() == out.len() && x.len().is_multiple_of(8),
38        "whole vectors"
39    );
40    for (x, out) in x.as_chunks::<8>().0.iter().zip(out.as_chunks_mut::<8>().0) {
41        // SAFETY: AVX2 and FMA were detected; x and out hold eight values.
42        unsafe {
43            _mm256_storeu_ps(
44                out.as_mut_ptr(),
45                math::avx2::gelu(_mm256_loadu_ps(x.as_ptr())),
46            )
47        };
48    }
49}
50
51/// Equal lengths divisible by eight; needs AVX2 and FMA.
52#[doc(hidden)]
53#[cfg(target_arch = "x86_64")]
54pub fn weight_indices(e: &[f32], out: &mut [u16]) {
55    attention::weight_indices_of(e, out);
56}
57
58/// Hashed with the [`Kernel`] into fingerprints, so any change to the arithmetic
59/// invalidates stored vectors and caches.
60pub const NUMERICAL_SOURCES: &[&[u8]] = &[
61    include_bytes!("encoder.rs"),
62    include_bytes!("gemm.rs"),
63    include_bytes!("math.rs"),
64    include_bytes!("attention.rs"),
65    include_bytes!("attention/integer.rs"),
66    include_bytes!("workers.rs"),
67    include_bytes!("lib.rs"),
68    include_bytes!("precision.rs"),
69    include_bytes!("projection.rs"),
70    include_bytes!("int8/mod.rs"),
71    include_bytes!("int8/prepared.rs"),
72    include_bytes!("int8/prepared/avx2.rs"),
73    include_bytes!("int8/activation_avx2.rs"),
74    include_bytes!("int8/e5_profile.rs"),
75    include_bytes!("int8/e5_v1_signs.bin"),
76    include_bytes!("int8/fused_epilogue.rs"),
77    include_bytes!("int8/gptq.rs"),
78];
79
80#[cfg(test)]
81mod tests {
82    use super::NUMERICAL_SOURCES;
83
84    /// The manifest stays out of the fingerprint: `cargo publish` rewrites it.
85    #[test]
86    fn fingerprint_inputs_exclude_the_manifest() {
87        let manifest: &[u8] = include_bytes!("../Cargo.toml");
88        assert!(!NUMERICAL_SOURCES.contains(&manifest));
89    }
90
91    /// Every source outside the tests is hashed, so editing any of them changes the fingerprint.
92    #[test]
93    fn every_source_is_a_fingerprint_input() {
94        let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
95        let mut dirs = vec![src];
96        while let Some(dir) = dirs.pop() {
97            for entry in std::fs::read_dir(dir).unwrap() {
98                let path = entry.unwrap().path();
99                let name = path.file_name().unwrap().to_str().unwrap();
100                if name == "tests" || name == "tests.rs" || name.ends_with("_tests.rs") {
101                    continue;
102                }
103                if path.is_dir() {
104                    dirs.push(path);
105                } else {
106                    let source = std::fs::read(&path).unwrap();
107                    assert!(
108                        NUMERICAL_SOURCES.contains(&source.as_slice()),
109                        "{} is not hashed",
110                        path.display()
111                    );
112                }
113            }
114        }
115    }
116}