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
423
424
425
#[cfg(feature = "hf-hub")]
use crate::common::HubRepo;
#[cfg(feature = "hf-hub")]
use crate::common::{init_session_builder, load_tokenizer_hf_hub};
use crate::{
    common::{encode_batch, load_tokenizer, Error, Result},
    models::bgem3::{models_list, Bgem3Model},
    text_embedding::InitOptionsUserDefined,
    ModelInfo, SparseEmbedding, TokenizerFiles,
};
use ndarray::{Array2, ArrayViewD};
use ort::session::Session;
use std::collections::HashMap;
#[cfg(feature = "hf-hub")]
use std::path::PathBuf;
use tokenizers::Tokenizer;

#[cfg(feature = "hf-hub")]
use super::Bgem3InitOptions;
use super::{Bgem3Embedding, Bgem3EmbeddingOutput, UserDefinedBgem3Model, DEFAULT_BATCH_SIZE};

impl Bgem3Embedding {
    /// Try to generate a new Bgem3Embedding 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: Bgem3InitOptions) -> Result<Self> {
        let Bgem3InitOptions {
            max_length,
            model_name,
            cache_dir,
            show_download_progress,
            environment,
            execution_providers,
            intra_threads,
            session_config,
            auto_device,
        } = options;

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

        let model_info = Bgem3Embedding::get_model_info(&model_name);
        let model_file_name = &model_info.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),
                })?;

        // Download additional files if needed
        for file in &model_info.additional_files {
            model_repo.get(file).map_err(|e| Error::ModelRetrieval {
                file: file.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)?;

        let tokenizer = load_tokenizer_hf_hub(model_repo, max_length)?;
        Ok(Self::new(tokenizer, session, model_name))
    }

    /// Create a Bgem3Embedding instance from model files provided by the user.
    pub fn try_new_from_user_defined(
        model: UserDefinedBgem3Model,
        options: InitOptionsUserDefined,
    ) -> Result<Self> {
        let (mut session_builder, max_length) = options.into_session_builder()?;
        let session = session_builder.commit_from_memory(&model.onnx_file)?;

        let tokenizer = load_tokenizer(model.tokenizer_files, max_length)?;
        Ok(Self::new(tokenizer, session, Bgem3Model::default()))
    }

    /// Create a Bgem3Embedding instance from an ONNX model on disk.
    ///
    /// `model_path` is a `.onnx` file or a directory containing `model.onnx`.
    /// Supports split external data files (model.onnx + model.onnx_data).
    pub fn try_new_from_path(
        model_path: impl AsRef<std::path::Path>,
        tokenizer_files: TokenizerFiles,
        options: InitOptionsUserDefined,
    ) -> Result<Self> {
        let model_path = model_path.as_ref();
        let model_file = if model_path.is_dir() {
            model_path.join("model.onnx")
        } else {
            model_path.to_path_buf()
        };

        let (mut session_builder, max_length) = options.into_session_builder()?;
        let session = session_builder.commit_from_file(model_file)?;

        let tokenizer = load_tokenizer(tokenizer_files, max_length)?;
        Ok(Self::new(tokenizer, session, Bgem3Model::default()))
    }

    /// Private method to return an instance
    fn new(tokenizer: Tokenizer, session: Session, model: Bgem3Model) -> Self {
        let need_token_type_ids = session
            .inputs()
            .iter()
            .any(|input| input.name() == "token_type_ids");
        Self {
            tokenizer,
            session,
            need_token_type_ids,
            model,
        }
    }

    /// Return the Bgem3Embedding model's directory from cache or remote retrieval
    #[cfg(feature = "hf-hub")]
    fn retrieve_model(
        model: Bgem3Model,
        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<Bgem3Model>> {
        models_list()
    }

    /// Get ModelInfo from Bgem3Model
    pub fn get_model_info(model: &Bgem3Model) -> ModelInfo<Bgem3Model> {
        Bgem3Embedding::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.")
    }

    /// Method to generate sentence embeddings for a collection of texts.
    ///
    /// `Bgem3Model::BGEM3Q` is dynamically quantized, so the vectors of a text vary slightly
    /// with the other texts in its batch.
    pub fn embed<S: AsRef<str> + Send + Sync>(
        &mut self,
        texts: impl AsRef<[S]>,
        batch_size: Option<usize>,
    ) -> Result<Bgem3EmbeddingOutput> {
        let texts = texts.as_ref();
        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 mut all_dense = Vec::with_capacity(texts.len());
        let mut all_sparse = Vec::with_capacity(texts.len());
        let mut all_colbert = Vec::with_capacity(texts.len());

        for batch in texts.chunks(batch_size) {
            let inputs = batch.iter().map(|text| text.as_ref()).collect();
            let mut encoded = encode_batch(&self.tokenizer, inputs)?;
            let session_inputs = encoded.session_inputs(self.need_token_type_ids)?;
            let current_batch_size = encoded.input_ids.nrows();

            let outputs = self
                .session
                .run(session_inputs)
                .map_err(|e| Error::OrtSession(e.to_string()))?;
            if outputs.len() < 3 {
                return Err(Error::Other(format!(
                    "BGE-M3 expects the model to return 3 outputs (dense, sparse, colbert), got {}",
                    outputs.len()
                )));
            }

            // gpahal/bge-m3-onnx-int8 returns outputs in this exact order:
            // outputs[0] -> dense_vecs: [batch_size, 1024]
            // outputs[1] -> sparse_vecs: [batch_size, seq_len, 1]
            // outputs[2] -> colbert_vecs: [batch_size, seq_len - 1, 1024]

            let dense = output_view(&outputs[0])?;
            let sparse = output_view(&outputs[1])?;
            let sparse = sparse_embeddings(&sparse, &encoded.input_ids, &encoded.attention_mask)?;
            let colbert = output_view(&outputs[2])?;
            let colbert = colbert_vectors(&colbert, &encoded.attention_mask)?;

            all_dense.extend(dense_vectors(&dense, current_batch_size)?);
            all_sparse.extend(sparse);
            all_colbert.extend(colbert);
        }

        Ok(Bgem3EmbeddingOutput {
            dense: all_dense,
            sparse: all_sparse,
            colbert: all_colbert,
        })
    }
}

fn output_view<'a>(output: &'a ort::value::DynValue) -> Result<ArrayViewD<'a, f32>> {
    let (shape, data) = output
        .try_extract_tensor::<f32>()
        .map_err(|e| Error::TensorExtraction(e.to_string()))?;
    let shape: Vec<usize> = shape.iter().map(|&d| d as usize).collect();
    ArrayViewD::from_shape(shape, data).map_err(|e| Error::InvalidShape(e.to_string()))
}

/// One dense vector per text.
fn dense_vectors(dense: &ArrayViewD<f32>, texts: usize) -> Result<Vec<Vec<f32>>> {
    let vectors: Vec<Vec<f32>> = dense.rows().into_iter().map(|row| row.to_vec()).collect();
    if vectors.len() != texts {
        return Err(Error::InvalidShape(format!(
            "BGE-M3 dense output must have one row per text, got shape {:?} for {texts} texts",
            dense.shape()
        )));
    }
    Ok(vectors)
}

/// Per text, the largest positive weight of each token id, special tokens left out.
fn sparse_embeddings(
    sparse: &ArrayViewD<f32>,
    input_ids: &Array2<i64>,
    attention_mask: &Array2<i64>,
) -> Result<Vec<SparseEmbedding>> {
    // Special tokens to skip: XLM-RoBERTa: CLS=0, PAD=1, EOS=2, UNK=3
    const SPECIAL_TOKENS: [i64; 4] = [0, 1, 2, 3];

    let shape = sparse.shape();
    if shape.len() != 3 {
        return Err(Error::Other(format!(
            "BGE-M3 sparse output must be rank-3 [batch, seq_len, 1], got shape {shape:?}"
        )));
    }
    let (batch_size, encoding_length) = input_ids.dim();

    (0..batch_size)
        .map(|batch_idx| {
            let mut token_weights: HashMap<usize, f32> = HashMap::new();
            for seq_idx in 0..encoding_length {
                if attention_mask[[batch_idx, seq_idx]] == 0 {
                    continue;
                }

                let token_id = input_ids[[batch_idx, seq_idx]];
                if SPECIAL_TOKENS.contains(&token_id) {
                    continue;
                }

                let weight = *sparse.get([batch_idx, seq_idx, 0]).ok_or_else(|| {
                    Error::InvalidShape(format!(
                        "BGE-M3 sparse output of shape {shape:?} has no weight for token {seq_idx} of text {batch_idx}"
                    ))
                })?;
                if weight > 0.0 {
                    token_weights
                        .entry(token_id as usize)
                        .and_modify(|w| *w = w.max(weight))
                        .or_insert(weight);
                }
            }

            let mut indices: Vec<_> = token_weights.keys().copied().collect();
            indices.sort_unstable();
            let values: Vec<_> = indices.iter().map(|i| token_weights[i]).collect();

            Ok(SparseEmbedding { values, indices })
        })
        .collect()
}

/// Per text, the ColBERT vectors of its unmasked tokens after the first.
fn colbert_vectors(
    colbert: &ArrayViewD<f32>,
    attention_mask: &Array2<i64>,
) -> Result<Vec<Vec<Vec<f32>>>> {
    let shape = colbert.shape();
    let (batch_size, encoding_length) = attention_mask.dim();
    if shape.len() != 3 || shape[1] >= encoding_length {
        return Err(Error::Other(format!(
            "BGE-M3 colbert output must be rank-3 [batch, seq_len - 1, dim] with seq_len - 1 < {encoding_length}, got shape {shape:?}"
        )));
    }
    // Shape of colbert is [batch_size, seq_len - 1, 1024]
    let colbert_seq_len = shape[1];

    (0..batch_size)
        .map(|batch_idx| {
            let mut doc_colbert = Vec::new();
            for seq_idx in 0..colbert_seq_len {
                if attention_mask[[batch_idx, seq_idx + 1]] == 1 {
                    if batch_idx >= shape[0] {
                        return Err(Error::InvalidShape(format!(
                            "BGE-M3 colbert output of shape {shape:?} has no vectors for text {batch_idx}"
                        )));
                    }
                    let token_vector = colbert.slice(ndarray::s![batch_idx, seq_idx, ..]);
                    doc_colbert.push(token_vector.to_vec());
                }
            }
            Ok(doc_colbert)
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::{arr2, Array1, Array2, Array3};

    #[test]
    fn dense_vectors_takes_one_row_per_text() {
        let flat = Array2::from_shape_vec((2, 3), (0..6).map(|v| v as f32).collect()).unwrap();
        let rows = dense_vectors(&flat.view().into_dyn(), 2).unwrap();
        assert_eq!(rows, [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]);

        // Shapes 7.7.0 read one row per text from.
        let nested = Array3::<f32>::zeros((2, 1, 3)).into_dyn();
        assert_eq!(dense_vectors(&nested.view(), 2).unwrap().len(), 2);
        let single = Array1::<f32>::zeros(3).into_dyn();
        assert_eq!(dense_vectors(&single.view(), 1).unwrap().len(), 1);

        let per_token = Array3::<f32>::zeros((2, 4, 3)).into_dyn();
        assert!(matches!(
            dense_vectors(&per_token.view(), 2),
            Err(Error::InvalidShape(_))
        ));
    }

    #[test]
    fn sparse_embeddings_keeps_the_largest_positive_weight_per_token() {
        // <s>=0 and </s>=2 are special, 1 is padding. The second text has a masked 9.
        let input_ids = arr2(&[[0i64, 9, 7, 9, 2], [0, 7, 2, 9, 1]]);
        let attention_mask = arr2(&[[1i64, 1, 1, 1, 1], [1, 1, 1, 0, 0]]);
        let sparse = Array3::from_shape_vec(
            (2, 5, 1),
            vec![5.0, 0.6, -0.1, 0.2, 5.0, 5.0, 0.3, 5.0, 9.0, 9.0],
        )
        .unwrap()
        .into_dyn();

        let out = sparse_embeddings(&sparse.view(), &input_ids, &attention_mask).unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].indices, [9]);
        assert_eq!(out[0].values, [0.6]);
        assert_eq!(out[1].indices, [7]);
        assert_eq!(out[1].values, [0.3]);
    }

    #[test]
    fn sparse_embeddings_errors_where_a_token_has_no_weight() {
        let input_ids = arr2(&[[0i64, 9, 2], [0, 7, 2]]);
        let attention_mask = arr2(&[[1i64, 1, 1], [1, 1, 1]]);

        let rank2 = Array2::<f32>::zeros((2, 3)).into_dyn();
        assert!(sparse_embeddings(&rank2.view(), &input_ids, &attention_mask).is_err());
        let one_text = Array3::<f32>::zeros((1, 3, 1)).into_dyn();
        let no_width = Array3::<f32>::zeros((2, 3, 0)).into_dyn();
        for sparse in [one_text, no_width] {
            assert!(matches!(
                sparse_embeddings(&sparse.view(), &input_ids, &attention_mask),
                Err(Error::InvalidShape(_))
            ));
        }

        // The last token has no weight, and it is special, so nothing is read there.
        let last_token_missing = Array3::<f32>::ones((2, 2, 1)).into_dyn();
        let out =
            sparse_embeddings(&last_token_missing.view(), &input_ids, &attention_mask).unwrap();
        assert_eq!(out[0].indices, [9]);
        // Rows and positions past the input are left unread, as before.
        let larger = Array3::<f32>::ones((3, 6, 2)).into_dyn();
        assert!(sparse_embeddings(&larger.view(), &input_ids, &attention_mask).is_ok());
    }

    #[test]
    fn colbert_vectors_takes_the_unmasked_tokens_after_the_first() {
        let attention_mask = arr2(&[[1i64, 1, 1], [1, 1, 0]]);
        let colbert = Array3::from_shape_vec((2, 2, 2), (0..8).map(|v| v as f32).collect())
            .unwrap()
            .into_dyn();

        let out = colbert_vectors(&colbert.view(), &attention_mask).unwrap();
        assert_eq!(out[0], [[0.0, 1.0], [2.0, 3.0]]);
        assert_eq!(out[1], [[4.0, 5.0]]);
    }

    #[test]
    fn colbert_vectors_errors_on_shapes_it_cannot_read() {
        let attention_mask = arr2(&[[1i64, 1, 1], [1, 1, 0]]);

        let rank2 = Array2::<f32>::zeros((2, 2)).into_dyn();
        assert!(colbert_vectors(&rank2.view(), &attention_mask).is_err());
        let full_length = Array3::<f32>::zeros((2, 3, 2)).into_dyn();
        assert!(colbert_vectors(&full_length.view(), &attention_mask).is_err());
        let one_text = Array3::<f32>::zeros((1, 2, 2)).into_dyn();
        assert!(matches!(
            colbert_vectors(&one_text.view(), &attention_mask),
            Err(Error::InvalidShape(_))
        ));
        // An extra row is left unread, as before.
        let larger = Array3::<f32>::zeros((3, 2, 2)).into_dyn();
        assert_eq!(
            colbert_vectors(&larger.view(), &attention_mask)
                .unwrap()
                .len(),
            2
        );
    }
}