fastembed 7.7.1

Library for generating vector embeddings, reranking locally.
Documentation
use super::utils::{Compose, ResizeFn};
use crate::{
    init::{InitOptions, ProviderNames},
    ImageEmbeddingModel,
};
use image::DynamicImage;
use ndarray::Array3;
use ort::{
    environment::Environment,
    ep::ExecutionProviderDispatch,
    session::{builder::AutoDevicePolicy, Session},
};
use std::sync::Arc;

/// Options for initializing the ImageEmbedding model
pub type ImageInitOptions = InitOptions<ImageEmbeddingModel>;

/// Options for initializing UserDefinedImageEmbeddingModel
///
/// Model files are held by the UserDefinedImageEmbeddingModel struct
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct ImageInitOptionsUserDefined {
    pub environment: Option<Environment>,
    pub execution_providers: Vec<ExecutionProviderDispatch>,
    /// Number of intra-op threads for ONNX Runtime. `None` (the default) uses
    /// every available CPU core via `std::thread::available_parallelism`, or
    /// ONNX Runtime's own default when the core count cannot be read.
    /// Set this to cap CPU usage (e.g. on laptops) at the cost of throughput.
    pub intra_threads: Option<usize>,
    /// ONNX Runtime session configuration entries, applied with
    /// `SessionBuilder::with_config_entry`. Use this for settings that have
    /// no dedicated builder method, such as `mlas.disable_kleidiai`.
    pub session_config: Vec<(String, String)>,
    /// Policy for ONNX Runtime's automatic execution provider selection,
    /// applied with `SessionBuilder::with_auto_device`. `None` (the default)
    /// keeps ort's default, `AutoDevicePolicy::MaxEfficiency`, which registers
    /// CoreML on macOS. `Some(AutoDevicePolicy::PreferCPU)` never registers an
    /// execution provider automatically. Execution providers passed through
    /// `execution_providers` take precedence over automatic selection.
    pub auto_device: Option<AutoDevicePolicy>,
}

impl std::fmt::Debug for ImageInitOptionsUserDefined {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ImageInitOptionsUserDefined")
            .field("environment", &self.environment)
            .field(
                "execution_providers",
                &ProviderNames(&self.execution_providers),
            )
            .field("intra_threads", &self.intra_threads)
            .field("session_config", &self.session_config)
            .field("auto_device", &self.auto_device)
            .finish()
    }
}

impl ImageInitOptionsUserDefined {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_environment(mut self, environment: Environment) -> Self {
        self.environment = Some(environment);
        self
    }

    pub fn with_execution_providers(
        mut self,
        execution_providers: Vec<ExecutionProviderDispatch>,
    ) -> Self {
        self.execution_providers = execution_providers;
        self
    }

    /// Set the number of intra-op threads ONNX Runtime uses. By default
    /// (`None`) all available CPU cores are used. Capping this limits CPU
    /// usage at the cost of per-inference throughput.
    pub fn with_intra_threads(mut self, intra_threads: usize) -> Self {
        self.intra_threads = Some(intra_threads);
        self
    }

    /// Add an ONNX Runtime session configuration entry, applied with
    /// `SessionBuilder::with_config_entry`. Call it once per entry.
    /// Example: `.with_session_config("mlas.disable_kleidiai", "1")`.
    pub fn with_session_config(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.session_config.push((key.into(), value.into()));
        self
    }

    /// Set the policy for ONNX Runtime's automatic execution provider
    /// selection, applied with `SessionBuilder::with_auto_device`.
    /// Example: `.with_auto_device(AutoDevicePolicy::PreferCPU)` keeps every
    /// node on the CPU when no execution provider is registered explicitly.
    pub fn with_auto_device(mut self, policy: AutoDevicePolicy) -> Self {
        self.auto_device = Some(policy);
        self
    }
}

/// Convert ImageInitOptions to ImageInitOptionsUserDefined
///
/// This is useful for when the user wants to use the same options for both the default and user-defined models
impl From<ImageInitOptions> for ImageInitOptionsUserDefined {
    fn from(options: ImageInitOptions) -> Self {
        ImageInitOptionsUserDefined {
            environment: options.environment,
            execution_providers: options.execution_providers,
            intra_threads: options.intra_threads,
            session_config: options.session_config,
            auto_device: options.auto_device,
        }
    }
}

/// Struct for "bring your own" embedding models
///
/// The `onnx_file` and `preprocessor_file` fields contain the file contents as bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct UserDefinedImageEmbeddingModel {
    pub onnx_file: Vec<u8>,
    pub preprocessor_file: Vec<u8>,
}

impl UserDefinedImageEmbeddingModel {
    pub fn new(onnx_file: Vec<u8>, preprocessor_file: Vec<u8>) -> Self {
        Self {
            onnx_file,
            preprocessor_file,
        }
    }
}

/// A model-specific image preprocessor that can be shared with CPU worker threads.
///
/// The returned arrays are ready to pass to [`ImageEmbedding::embed_preprocessed`].
#[derive(Clone)]
pub struct ImagePreprocessor {
    inner: Arc<Compose>,
    resize: Option<Arc<ResizeFn>>,
}

impl ImagePreprocessor {
    pub(crate) fn new(inner: Compose) -> Self {
        Self {
            inner: Arc::new(inner),
            resize: None,
        }
    }

    /// Resize, crop, rescale, and normalize an image according to this model's configuration.
    pub fn preprocess(&self, image: DynamicImage) -> crate::Result<Array3<f32>> {
        let (width, height) = (image.width(), image.height());
        if width == 0 || height == 0 {
            return Err(crate::Error::ImageTransform(format!(
                "A {width}x{height} image has no pixels"
            )));
        }
        match &self.resize {
            Some(resize) => self
                .inner
                .preprocess_image_with_resize(image, resize.as_ref()),
            None => self.inner.preprocess_image(image),
        }
    }

    /// Use a custom image resize implementation while retaining the model-specific geometry,
    /// cropping, rescaling, and normalization stages.
    pub fn with_resize<F>(mut self, resize: F) -> Self
    where
        F: Fn(DynamicImage, u32, u32, image::imageops::FilterType) -> crate::Result<DynamicImage>
            + Send
            + Sync
            + 'static,
    {
        self.resize = Some(Arc::new(resize));
        self
    }
}

pub struct ImageEmbedding {
    pub(crate) preprocessor: ImagePreprocessor,
    pub(crate) session: Session,
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use image::RgbImage;

    use super::*;

    #[test]
    fn auto_device_is_carried_by_from() {
        let opts = ImageInitOptions::new(ImageEmbeddingModel::ClipVitB32)
            .with_auto_device(AutoDevicePolicy::PreferCPU);
        let user_defined = ImageInitOptionsUserDefined::from(opts);
        assert_eq!(user_defined.auto_device, Some(AutoDevicePolicy::PreferCPU));
    }

    #[test]
    fn an_image_without_pixels_is_refused() {
        let config = br#"{"do_resize": true, "size": {"shortest_edge": 224}}"#;
        let preprocessor = ImagePreprocessor::new(Compose::from_bytes(config).unwrap());
        for (width, height) in [(0, 5), (5, 0), (0, 0)] {
            assert!(matches!(
                preprocessor.preprocess(RgbImage::new(width, height).into()),
                Err(crate::Error::ImageTransform(_))
            ));
        }
    }

    #[test]
    fn a_custom_resizer_gets_every_size() {
        // The default resizer cannot allocate this size and refuses it.
        let config = br#"{"do_resize": true, "size": {"width": 4294967295, "height": 4294967295}}"#;
        let preprocessor = ImagePreprocessor::new(Compose::from_bytes(config).unwrap());
        assert!(preprocessor.preprocess(RgbImage::new(1, 1).into()).is_err());

        let preprocessor = preprocessor.with_resize(|_, width, height, _| {
            assert_eq!((width, height), (u32::MAX, u32::MAX));
            Ok(RgbImage::new(2, 2).into())
        });
        let pixels = preprocessor.preprocess(RgbImage::new(1, 1).into()).unwrap();
        assert_eq!(pixels.shape(), &[3, 2, 2]);
    }

    #[test]
    fn the_resizer_gets_the_filter_that_the_config_names() {
        use image::imageops::FilterType;

        for (resample, expected) in [
            ("", FilterType::CatmullRom),
            (r#""resample": 0,"#, FilterType::Nearest),
            (r#""resample": 1,"#, FilterType::Lanczos3),
            (r#""resample": 2,"#, FilterType::Triangle),
            (r#""resample": 3,"#, FilterType::CatmullRom),
            // PIL's box filter has no counterpart in the image crate.
            (r#""resample": 4,"#, FilterType::CatmullRom),
        ] {
            // ConvNext resizes to the exact size from a shortest edge of 384 on.
            for (processor, shortest_edge) in [
                ("CLIPImageProcessor", 4),
                ("BitImageProcessor", 4),
                ("ConvNextImageProcessor", 4),
                ("ConvNextImageProcessor", 384),
            ] {
                let config = format!(
                    r#"{{"image_processor_type": "{processor}", {resample}
                        "do_resize": true, "size": {{"shortest_edge": {shortest_edge}}}}}"#
                );
                let calls = Arc::new(AtomicUsize::new(0));
                let observed = Arc::clone(&calls);
                let preprocessor = ImagePreprocessor::new(Compose::from_bytes(config).unwrap())
                    .with_resize(move |image, _, _, filter| {
                        assert_eq!(filter, expected);
                        observed.fetch_add(1, Ordering::Relaxed);
                        Ok(image)
                    });
                preprocessor.preprocess(RgbImage::new(8, 8).into()).unwrap();
                assert_eq!(
                    calls.load(Ordering::Relaxed),
                    1,
                    "{processor} {shortest_edge} {resample}"
                );
            }
        }
    }

    #[test]
    fn cloneable_preprocessor_supports_a_custom_resizer() {
        let config = br#"{
            "image_processor_type": "CLIPImageProcessor",
            "do_resize": true,
            "size": { "height": 4, "width": 5 },
            "do_center_crop": true,
            "crop_size": { "height": 2, "width": 3 },
            "do_rescale": true,
            "rescale_factor": 0.5,
            "do_normalize": true,
            "image_mean": [1.0, 1.0, 1.0],
            "image_std": [2.0, 2.0, 2.0]
        }"#;
        let calls = Arc::new(AtomicUsize::new(0));
        let observed = Arc::clone(&calls);
        let preprocessor = ImagePreprocessor::new(Compose::from_bytes(config).unwrap())
            .with_resize(move |_, width, height, filter| {
                assert_eq!((width, height), (5, 4));
                assert_eq!(filter, image::imageops::FilterType::CatmullRom);
                observed.fetch_add(1, Ordering::Relaxed);
                Ok(RgbImage::from_pixel(width, height, image::Rgb([5, 7, 9])).into())
            });

        let pixels = preprocessor
            .clone()
            .preprocess(RgbImage::new(10, 20).into())
            .unwrap();

        assert_eq!(calls.load(Ordering::Relaxed), 1);
        assert_eq!(pixels.shape(), &[3, 2, 3]);
        assert_eq!(pixels[[0, 0, 0]], 0.75);
        assert_eq!(pixels[[1, 1, 1]], 1.25);
        assert_eq!(pixels[[2, 0, 2]], 1.75);
    }
}