fastembed 7.8.0

Library for generating vector embeddings, reranking locally.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
#[cfg(feature = "hf-hub")]
use crate::common::HubRepo;
use image::DynamicImage;
use ndarray::{Array3, ArrayView3};
use ort::{session::Session, value::Value};
#[cfg(feature = "hf-hub")]
use std::path::PathBuf;
use std::{io::Cursor, path::Path};

use crate::{
    common::{decode_image, init_session_builder, normalize, Error, Result},
    models::image_embedding::models_list,
    Embedding, ImageEmbeddingModel, ModelInfo,
};

#[cfg(feature = "hf-hub")]
use super::ImageInitOptions;
use super::{
    init::{ImageInitOptionsUserDefined, UserDefinedImageEmbeddingModel},
    utils::Compose,
    ImageEmbedding, ImagePreprocessor, DEFAULT_BATCH_SIZE,
};

impl ImageEmbedding {
    /// Try to generate a new ImageEmbedding Instance
    ///
    /// Uses the highest level of Graph optimization
    ///
    /// Uses the total number of CPUs available as the number of intra-threads
    #[cfg(feature = "hf-hub")]
    pub fn try_new(options: ImageInitOptions) -> Result<Self> {
        let ImageInitOptions {
            model_name,
            environment,
            execution_providers,
            cache_dir,
            show_download_progress,
            intra_threads,
            session_config,
            auto_device,
        } = options;

        let model_repo = ImageEmbedding::retrieve_model(
            model_name.clone(),
            cache_dir.clone(),
            show_download_progress,
        )?;

        let preprocessor_file =
            model_repo
                .get("preprocessor_config.json")
                .map_err(|e| Error::ModelRetrieval {
                    file: "preprocessor_config.json".into(),
                    source: Box::new(e),
                })?;
        let preprocessor = ImagePreprocessor::new(Compose::from_file(preprocessor_file)?);

        let model_file_name = ImageEmbedding::get_model_info(&model_name).model_file;
        let model_file_reference =
            model_repo
                .get(&model_file_name)
                .map_err(|e| Error::ModelRetrieval {
                    file: model_file_name.clone(),
                    source: Box::new(e),
                })?;

        let session = init_session_builder(
            environment,
            execution_providers,
            intra_threads,
            session_config,
            auto_device,
        )?
        .commit_from_file(model_file_reference)?;

        Ok(Self::new(preprocessor, session))
    }

    /// Create a ImageEmbedding instance from model files provided by the user.
    ///
    /// This can be used for 'bring your own' embedding models
    pub fn try_new_from_user_defined(
        model: UserDefinedImageEmbeddingModel,
        options: ImageInitOptionsUserDefined,
    ) -> Result<Self> {
        let ImageInitOptionsUserDefined {
            environment,
            execution_providers,
            intra_threads,
            session_config,
            auto_device,
        } = options;

        let preprocessor = ImagePreprocessor::new(Compose::from_bytes(model.preprocessor_file)?);

        let session = init_session_builder(
            environment,
            execution_providers,
            intra_threads,
            session_config,
            auto_device,
        )?
        .commit_from_memory(&model.onnx_file)?;

        Ok(Self::new(preprocessor, session))
    }

    /// Private method to return an instance
    fn new(preprocessor: ImagePreprocessor, session: Session) -> Self {
        Self {
            preprocessor,
            session,
        }
    }

    /// Return the ImageEmbedding model's directory from cache or remote retrieval
    #[cfg(feature = "hf-hub")]
    fn retrieve_model(
        model: ImageEmbeddingModel,
        cache_dir: PathBuf,
        show_download_progress: bool,
    ) -> Result<HubRepo> {
        use crate::common::pull_from_hf;

        pull_from_hf(model.to_string(), cache_dir, show_download_progress)
    }

    /// Retrieve a list of supported models
    pub fn list_supported_models() -> Vec<ModelInfo<ImageEmbeddingModel>> {
        models_list()
    }

    /// Get ModelInfo from ImageEmbeddingModel
    pub fn get_model_info(model: &ImageEmbeddingModel) -> ModelInfo<ImageEmbeddingModel> {
        ImageEmbedding::list_supported_models()
            .into_iter()
            .find(|m| &m.model == model)
            .expect("Model not found in supported models list. This is a bug - please report it.")
    }

    /// Return a cloneable CPU preprocessor configured for this image model.
    ///
    /// Use it to preprocess images on worker threads, then pass the resulting arrays to
    /// [`Self::embed_preprocessed`].
    pub fn preprocessor(&self) -> ImagePreprocessor {
        self.preprocessor.clone()
    }

    /// Method to generate image embeddings for a Vec of image bytes
    pub fn embed_bytes(
        &mut self,
        images: &[&[u8]],
        batch_size: Option<usize>,
    ) -> Result<Vec<Embedding>> {
        let batch_size = batch_size.unwrap_or(DEFAULT_BATCH_SIZE);
        if batch_size == 0 {
            return Err(Error::InvalidArgument(
                "batch_size must be greater than 0".into(),
            ));
        }

        let output = images
            .chunks(batch_size)
            .map(|batch| {
                let inputs = self.preprocess_batch(batch, |img| {
                    image::ImageReader::new(Cursor::new(img))
                        .with_guessed_format()?
                        .decode()
                        .map_err(|err| Error::ImageDecode(err.to_string()))
                })?;

                self.embed_preprocessed(inputs)
            })
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .flatten()
            .collect();

        Ok(output)
    }

    /// Method to generate image embeddings for a collection of image paths.
    ///
    /// Accepts anything that can be referenced as a slice of elements implementing
    /// [`AsRef<Path>`], such as `Vec<String>`, `Vec<PathBuf>`, `&[&str]`, or `&[&Path]`.
    pub fn embed<S: AsRef<Path> + Send + Sync>(
        &mut self,
        images: impl AsRef<[S]>,
        batch_size: Option<usize>,
    ) -> Result<Vec<Embedding>> {
        let images = images.as_ref();
        // Determine the batch size, default if not specified
        let batch_size = batch_size.unwrap_or(DEFAULT_BATCH_SIZE);
        if batch_size == 0 {
            return Err(Error::InvalidArgument(
                "batch_size must be greater than 0".into(),
            ));
        }

        let output = images
            .chunks(batch_size)
            .map(|batch| {
                let inputs = self.preprocess_batch(batch, |img| {
                    let reader = image::ImageReader::open(img)?;
                    decode_image(img.as_ref(), reader)
                        .map_err(|err| Error::ImageDecode(err.to_string()))
                })?;

                self.embed_preprocessed(inputs)
            })
            .collect::<Result<Vec<_>>>()?
            .into_iter()
            .flatten()
            .collect();

        Ok(output)
    }

    /// Decodes and preprocesses the images of one batch, one image at a time, so that the
    /// batch holds only the model inputs. When an image fails to preprocess, the images after
    /// it are still decoded: an error in decoding one of them comes first, as it does when the
    /// whole batch is decoded before it is preprocessed.
    fn preprocess_batch<T>(
        &self,
        batch: &[T],
        decode: impl Fn(&T) -> Result<DynamicImage>,
    ) -> Result<Vec<Array3<f32>>> {
        let mut inputs = Vec::with_capacity(batch.len());
        for (index, image) in batch.iter().enumerate() {
            match self.preprocessor.preprocess(decode(image)?) {
                Ok(input) => inputs.push(input),
                Err(error) => {
                    for later in &batch[index + 1..] {
                        decode(later)?;
                    }
                    return Err(error);
                }
            }
        }
        Ok(inputs)
    }

    /// Embed DynamicImages
    pub fn embed_images(&mut self, imgs: Vec<DynamicImage>) -> Result<Vec<Embedding>> {
        let inputs = imgs
            .into_iter()
            .map(|img| self.preprocessor.preprocess(img))
            .collect::<Result<Vec<Array3<f32>>>>()?;
        self.embed_preprocessed(inputs)
    }

    /// Embed images already prepared by this model's [`ImagePreprocessor`].
    ///
    /// This separates CPU image preprocessing from mutable ONNX Runtime inference, allowing
    /// callers to prepare later batches while the accelerator processes the current batch.
    pub fn embed_preprocessed(&mut self, inputs: Vec<Array3<f32>>) -> Result<Vec<Embedding>> {
        if inputs.is_empty() {
            return Ok(Vec::new());
        }
        // Extract the batch size
        let inputs_view: Vec<ArrayView3<f32>> = inputs.iter().map(|img| img.view()).collect();
        let pixel_values_array = ndarray::stack(ndarray::Axis(0), &inputs_view)
            .map_err(|e| Error::InvalidShape(e.to_string()))?;

        let input_name = self.session.inputs()[0].name().to_string();
        let session_inputs = ort::inputs![
            input_name => Value::from_array(pixel_values_array)
                .map_err(|e| Error::OrtSession(e.to_string()))?,
        ];

        let outputs = self
            .session
            .run(session_inputs)
            .map_err(|e| Error::OrtSession(e.to_string()))?;

        // Try to get the only output key
        // If multiple, then default to few known keys `image_embeds` and `last_hidden_state`
        let last_hidden_state_key = match outputs.len() {
            1 => vec![outputs
                .keys()
                .next()
                .ok_or_else(|| Error::OutputKeyMissing {
                    key: "<only output>".into(),
                })?],
            _ => vec!["image_embeds", "last_hidden_state"],
        };

        // Extract tensor and handle different dimensionalities
        let (shape, data) = last_hidden_state_key
            .iter()
            .find_map(|&key| {
                outputs
                    .get(key)
                    .and_then(|v| v.try_extract_tensor::<f32>().ok())
            })
            .ok_or_else(|| {
                Error::TensorExtraction("Could not extract tensor from any known output key".into())
            })?;
        let shape: Vec<usize> = shape.iter().map(|&d| d as usize).collect();
        let output_array = ndarray::ArrayViewD::from_shape(shape.as_slice(), data)
            .map_err(|e| Error::InvalidShape(e.to_string()))?;

        let embeddings = match output_array.ndim() {
            3 => {
                // For 3D output [batch_size, sequence_length, hidden_size]
                // Take only the first token, sequence_length[0] (CLS token), embedding
                // and return [batch_size, hidden_size]
                (0..output_array.shape()[0])
                    .map(|batch_idx| {
                        let cls_embedding = output_array
                            .slice(ndarray::s![batch_idx, 0, ..])
                            .to_owned()
                            .to_vec();
                        normalize(&cls_embedding)
                    })
                    .collect()
            }
            2 => {
                // For 2D output [batch_size, hidden_size]
                output_array
                    .outer_iter()
                    .map(|row| {
                        row.as_slice()
                            .ok_or_else(|| {
                                Error::Other("Failed to convert array row to slice".into())
                            })
                            .map(normalize)
                    })
                    .collect::<Result<Vec<_>>>()?
            }
            _ => {
                return Err(Error::InvalidShape(format!(
                    "Unexpected output tensor shape: {:?}",
                    output_array.shape()
                )))
            }
        };

        Ok(embeddings)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_empty_batch_embeds_to_nothing() {
        let model = UserDefinedImageEmbeddingModel::new(
            crate::common::tests::relu_model_bytes(),
            br#"{"do_resize": false}"#.to_vec(),
        );
        let mut model =
            ImageEmbedding::try_new_from_user_defined(model, Default::default()).unwrap();
        assert!(model.embed_preprocessed(Vec::new()).unwrap().is_empty());
        assert!(model.embed_images(Vec::new()).unwrap().is_empty());
    }

    #[test]
    fn embed_reads_an_image_whose_extension_names_another_format() {
        use crate::common::image_tests::{png, Files};

        let model = UserDefinedImageEmbeddingModel::new(
            crate::common::tests::relu_model_bytes(),
            br#"{"do_resize": false}"#.to_vec(),
        );
        let mut model =
            ImageEmbedding::try_new_from_user_defined(model, Default::default()).unwrap();
        let files = Files::new("embed");
        let png_as_jpg = files.write("image.jpg", &png());
        let garbage = files.write("garbage.jpg", b"not an image");

        // The test model takes no image, so a decoded image fails later, in the session.
        assert!(matches!(
            model.embed([&png_as_jpg], None),
            Err(Error::OrtSession(_))
        ));
        assert!(matches!(
            model.embed([&garbage], None),
            Err(Error::ImageDecode(_))
        ));
    }

    #[test]
    fn a_decode_error_comes_before_a_preprocessing_error_of_an_earlier_image() {
        use crate::common::image_tests::{png, Files};

        // One mean for three channels: every image fails to preprocess.
        let config =
            br#"{"do_resize": false, "do_normalize": true, "image_mean": [0.5], "image_std": [0.5]}"#;
        let model = UserDefinedImageEmbeddingModel::new(
            crate::common::tests::relu_model_bytes(),
            config.to_vec(),
        );
        let mut model =
            ImageEmbedding::try_new_from_user_defined(model, Default::default()).unwrap();
        let files = Files::new("precedence");
        let valid = files.write("valid.png", &png());
        let garbage = files.write("garbage.png", b"not an image");

        assert!(matches!(
            model.embed([&valid], None),
            Err(Error::InvalidShape(_))
        ));
        for images in [[&valid, &garbage], [&garbage, &valid]] {
            assert!(matches!(
                model.embed(images, None),
                Err(Error::ImageDecode(_))
            ));
        }
        let (valid_bytes, garbage_bytes) = (png(), b"not an image".to_vec());
        assert!(matches!(
            model.embed_bytes(&[&valid_bytes, &garbage_bytes], None),
            Err(Error::ImageDecode(_))
        ));
        // In separate batches the first batch fails before the second is decoded.
        assert!(matches!(
            model.embed([&valid, &garbage], Some(1)),
            Err(Error::InvalidShape(_))
        ));
    }
}