Skip to main content

fastembed/
common.rs

1#[cfg(all(
2    feature = "hf-hub",
3    any(feature = "onnx", feature = "qwen3-text", feature = "nomic-v2-moe")
4))]
5use hf_hub::api::sync::{ApiBuilder, ApiRepo};
6#[cfg(feature = "onnx")]
7use ndarray::Array2;
8#[cfg(feature = "onnx")]
9use ort::{
10    environment::Environment,
11    ep::ExecutionProviderDispatch,
12    session::{
13        builder::{GraphOptimizationLevel, SessionBuilder},
14        SessionInputValue,
15    },
16    value::Value,
17};
18#[cfg(feature = "onnx")]
19use std::borrow::Cow;
20#[cfg(all(
21    feature = "hf-hub",
22    any(feature = "onnx", feature = "qwen3-text", feature = "nomic-v2-moe")
23))]
24use std::path::PathBuf;
25#[cfg(feature = "onnx")]
26use std::sync::{Mutex, PoisonError};
27#[cfg(feature = "onnx")]
28use tokenizers::{
29    AddedToken, EncodeInput, Encoding, PaddingParams, PaddingStrategy, Tokenizer, TruncationParams,
30};
31
32const DEFAULT_CACHE_DIR: &str = ".fastembed_cache";
33
34pub fn get_cache_dir() -> String {
35    std::env::var("FASTEMBED_CACHE_DIR").unwrap_or(DEFAULT_CACHE_DIR.into())
36}
37
38#[derive(Debug, Clone, PartialEq)]
39pub struct SparseEmbedding {
40    pub indices: Vec<usize>,
41    pub values: Vec<f32>,
42}
43
44/// Type alias for the embedding vector
45pub type Embedding = Vec<f32>;
46
47/// Error type returned by fastembed.
48#[derive(Debug, thiserror::Error)]
49#[non_exhaustive]
50pub enum Error {
51    #[error("Failed to retrieve model file '{file}'")]
52    ModelRetrieval {
53        file: String,
54        #[source]
55        source: Box<dyn std::error::Error + Send + Sync>,
56    },
57
58    #[error("Invalid tokenizer configuration: {0}")]
59    TokenizerConfig(String),
60
61    #[error("Failed to tokenize input: {0}")]
62    Tokenization(String),
63
64    #[error("Tokenizer returned empty encodings for the batch")]
65    EmptyTokenizations,
66
67    #[cfg(feature = "onnx")]
68    #[error("ONNX runtime error: {0}")]
69    Ort(#[from] ort::Error),
70
71    #[error("Failed to build ONNX session: {0}")]
72    OrtBuilder(String),
73
74    #[error("ONNX session error: {0}")]
75    OrtSession(String),
76
77    #[error("Output tensor '{key}' not found")]
78    OutputKeyMissing { key: String },
79
80    #[error("Failed to extract tensor: {0}")]
81    TensorExtraction(String),
82
83    #[error("Failed to decode image: {0}")]
84    ImageDecode(String),
85
86    #[error("Invalid preprocessor configuration: {0}")]
87    PreprocessorConfig(String),
88
89    #[error("Image transform error: {0}")]
90    ImageTransform(String),
91
92    #[error("Invalid tensor shape: {0}")]
93    InvalidShape(String),
94
95    #[error("Invalid argument: {0}")]
96    InvalidArgument(String),
97
98    #[error("I/O error: {0}")]
99    Io(#[from] std::io::Error),
100
101    #[error("an ONNX Runtime environment already exists in this process, pass it with `with_environment`")]
102    EnvironmentRequired,
103
104    #[error("{0}")]
105    Other(String),
106}
107
108/// Type alias for `Result` returning the fastembed [`Error`] type.
109pub type Result<T> = std::result::Result<T, Error>;
110
111#[cfg(feature = "hf-hub")]
112impl From<hf_hub::api::sync::ApiError> for Error {
113    fn from(e: hf_hub::api::sync::ApiError) -> Self {
114        Error::Other(format!("HuggingFace API error: {e}"))
115    }
116}
117
118// Tokenizer files for "bring your own" models
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct TokenizerFiles {
121    pub tokenizer_file: Vec<u8>,
122    pub config_file: Vec<u8>,
123    pub special_tokens_map_file: Vec<u8>,
124    pub tokenizer_config_file: Vec<u8>,
125}
126
127/// Loading tokenizer files from the Hugging Face Hub is separate from the main
128/// `load_tokenizer` function, which expects bytes from any source.
129#[cfg(all(feature = "onnx", feature = "hf-hub"))]
130pub fn load_tokenizer_hf_hub(model_repo: ApiRepo, max_length: usize) -> Result<Tokenizer> {
131    let tokenizer_files: TokenizerFiles = TokenizerFiles {
132        tokenizer_file: std::fs::read(model_repo.get("tokenizer.json")?)?,
133        config_file: std::fs::read(&model_repo.get("config.json")?)?,
134        special_tokens_map_file: std::fs::read(&model_repo.get("special_tokens_map.json")?)?,
135
136        tokenizer_config_file: std::fs::read(&model_repo.get("tokenizer_config.json")?)?,
137    };
138
139    load_tokenizer(tokenizer_files, max_length)
140}
141
142/// Function can be called directly from the try_new_from_user_defined function (providing file bytes)
143///
144/// Or indirectly from the try_new function via load_tokenizer_hf_hub (converting HF files to bytes)
145#[cfg(feature = "onnx")]
146pub fn load_tokenizer(tokenizer_files: TokenizerFiles, max_length: usize) -> Result<Tokenizer> {
147    let base_error_message =
148        "Error building TokenizerFiles for UserDefinedEmbeddingModel. Could not read {} file.";
149
150    // Deserialize each tokenizer file
151    let config: serde_json::Value =
152        serde_json::from_slice(&tokenizer_files.config_file).map_err(|_| {
153            std::io::Error::new(
154                std::io::ErrorKind::InvalidData,
155                base_error_message.replace("{}", "config.json"),
156            )
157        })?;
158    let special_tokens_map: serde_json::Value =
159        serde_json::from_slice(&tokenizer_files.special_tokens_map_file).map_err(|_| {
160            std::io::Error::new(
161                std::io::ErrorKind::InvalidData,
162                base_error_message.replace("{}", "special_tokens_map.json"),
163            )
164        })?;
165    let tokenizer_config: serde_json::Value =
166        serde_json::from_slice(&tokenizer_files.tokenizer_config_file).map_err(|_| {
167            std::io::Error::new(
168                std::io::ErrorKind::InvalidData,
169                base_error_message.replace("{}", "tokenizer_config.json"),
170            )
171        })?;
172    let mut tokenizer: tokenizers::Tokenizer =
173        tokenizers::Tokenizer::from_bytes(tokenizer_files.tokenizer_file).map_err(|_| {
174            std::io::Error::new(
175                std::io::ErrorKind::InvalidData,
176                base_error_message.replace("{}", "tokenizer.json"),
177            )
178        })?;
179
180    // For BGEBaseSmall, model_max_length is set to 1000000000000000019884624838656.
181    // This value fits in an f64.
182    let model_max_length = tokenizer_config["model_max_length"]
183        .as_f64()
184        .ok_or_else(|| {
185            Error::TokenizerConfig(
186                "tokenizer_config.json is missing a numeric `model_max_length` field".into(),
187            )
188        })? as f32;
189    let max_length = max_length.min(model_max_length as usize);
190    let pad_token_value = &tokenizer_config["pad_token"];
191    let pad_token: String = pad_token_value
192        .as_str()
193        .or_else(|| pad_token_value["content"].as_str())
194        .ok_or_else(|| {
195            Error::TokenizerConfig(
196                "tokenizer_config.json is missing a string `pad_token` field".into(),
197            )
198        })?
199        .into();
200    let pad_id = config["pad_token_id"]
201        .as_u64()
202        .map(|id| id as u32)
203        .or_else(|| tokenizer.token_to_id(&pad_token))
204        .unwrap_or(0);
205
206    let mut tokenizer = tokenizer
207        .with_padding(Some(PaddingParams {
208            // TODO: the user should be able to choose the padding strategy
209            strategy: PaddingStrategy::BatchLongest,
210            pad_token,
211            pad_id,
212            ..Default::default()
213        }))
214        .with_truncation(Some(TruncationParams {
215            max_length,
216            ..Default::default()
217        }))
218        .map_err(|e| Error::TokenizerConfig(e.to_string()))?
219        .clone();
220    if let serde_json::Value::Object(root_object) = special_tokens_map {
221        for (_, value) in root_object.iter() {
222            if value.is_string() {
223                if let Some(content) = value.as_str() {
224                    tokenizer
225                        .add_special_tokens([AddedToken {
226                            content: content.into(),
227                            special: true,
228                            ..Default::default()
229                        }])
230                        .map_err(|e| Error::TokenizerConfig(e.to_string()))?;
231                }
232            } else if value.is_object() {
233                if let (
234                    Some(content),
235                    Some(single_word),
236                    Some(lstrip),
237                    Some(rstrip),
238                    Some(normalized),
239                ) = (
240                    value["content"].as_str(),
241                    value["single_word"].as_bool(),
242                    value["lstrip"].as_bool(),
243                    value["rstrip"].as_bool(),
244                    value["normalized"].as_bool(),
245                ) {
246                    tokenizer
247                        .add_special_tokens([AddedToken {
248                            content: content.into(),
249                            special: true,
250                            single_word,
251                            lstrip,
252                            rstrip,
253                            normalized,
254                        }])
255                        .map_err(|e| Error::TokenizerConfig(e.to_string()))?;
256                }
257            }
258        }
259    }
260    Ok(tokenizer.into())
261}
262
263#[cfg(feature = "onnx")]
264pub fn normalize(v: &[f32]) -> Vec<f32> {
265    let norm = (v.iter().map(|val| val * val).sum::<f32>()).sqrt();
266    let epsilon = 1e-12;
267
268    // We add the super-small epsilon to avoid dividing by zero
269    v.iter().map(|&val| val / (norm + epsilon)).collect()
270}
271
272/// Pulls a model repo from HuggingFace.
273/// HF_HOME decides the location of the cache folder
274/// HF_ENDPOINT modifies the URL for the HuggingFace location.
275/// HF_TOKEN authenticates the requests. Without it the token written by
276/// `huggingface-cli login` is used when present.
277#[cfg(all(
278    feature = "hf-hub",
279    any(feature = "onnx", feature = "qwen3-text", feature = "nomic-v2-moe")
280))]
281pub fn pull_from_hf(
282    model_name: String,
283    default_cache_dir: PathBuf,
284    show_download_progress: bool,
285) -> Result<ApiRepo> {
286    use std::env;
287
288    let cache_dir = env::var("HF_HOME")
289        .map(PathBuf::from)
290        .unwrap_or(default_cache_dir);
291
292    let endpoint = env::var("HF_ENDPOINT").unwrap_or_else(|_| "https://huggingface.co".to_string());
293
294    let token = env::var("HF_TOKEN")
295        .ok()
296        .map(|token| token.trim().to_string())
297        .filter(|token| !token.is_empty())
298        .or_else(default_hf_token);
299
300    let api = ApiBuilder::new()
301        .with_cache_dir(cache_dir)
302        .with_endpoint(endpoint)
303        .with_token(token)
304        .with_progress(show_download_progress)
305        .build()
306        .map_err(|e| Error::Other(format!("Failed to initialize HuggingFace API: {e}")))?;
307
308    let repo = api.model(model_name);
309    Ok(repo)
310}
311
312/// Token written by `huggingface-cli login`. `Cache::default` panics without a home dir.
313#[cfg(all(
314    feature = "hf-hub",
315    any(feature = "onnx", feature = "qwen3-text", feature = "nomic-v2-moe")
316))]
317fn default_hf_token() -> Option<String> {
318    let has_home = std::env::var_os("HOME").is_some() || std::env::var_os("USERPROFILE").is_some();
319    has_home.then(|| hf_hub::Cache::default().token()).flatten()
320}
321
322/// Safetensors files of a repo, resolving `model.safetensors.index.json` for sharded checkpoints.
323#[cfg(all(
324    feature = "hf-hub",
325    any(feature = "qwen3-text", feature = "nomic-v2-moe")
326))]
327pub(crate) fn safetensors_weight_files(repo: &ApiRepo) -> Result<Vec<PathBuf>> {
328    const SINGLE_FILE: &str = "model.safetensors";
329    const INDEX_FILE: &str = "model.safetensors.index.json";
330
331    if let Ok(path) = repo.get(SINGLE_FILE) {
332        return Ok(vec![path]);
333    }
334
335    let index_path = repo.get(INDEX_FILE).map_err(|e| Error::ModelRetrieval {
336        file: format!("{SINGLE_FILE} or {INDEX_FILE}"),
337        source: Box::new(e),
338    })?;
339    let index: serde_json::Value = serde_json::from_slice(&std::fs::read(index_path)?)
340        .map_err(|e| Error::Other(format!("Failed to parse {INDEX_FILE}: {e}")))?;
341
342    let mut shards: Vec<String> = index["weight_map"]
343        .as_object()
344        .ok_or_else(|| Error::Other(format!("{INDEX_FILE} has no `weight_map` object")))?
345        .values()
346        .filter_map(|file| file.as_str().map(str::to_string))
347        .collect();
348    shards.sort_unstable();
349    shards.dedup();
350
351    shards
352        .iter()
353        .map(|file| {
354            repo.get(file).map_err(|e| Error::ModelRetrieval {
355                file: file.clone(),
356                source: Box::new(e),
357            })
358        })
359        .collect()
360}
361
362/// One tokenized batch as `[batch, sequence]` tensors.
363#[cfg(feature = "onnx")]
364pub(crate) struct EncodedBatch {
365    pub input_ids: Array2<i64>,
366    pub attention_mask: Array2<i64>,
367    pub token_type_ids: Array2<i64>,
368}
369
370#[cfg(feature = "onnx")]
371impl EncodedBatch {
372    /// ONNX session inputs. `token_type_ids` is moved out and attached only when the graph
373    /// declares it, while `input_ids` and `attention_mask` stay available for post-processing.
374    pub fn session_inputs(
375        &mut self,
376        need_token_type_ids: bool,
377    ) -> Result<Vec<(Cow<'static, str>, SessionInputValue<'static>)>> {
378        let mut inputs = ort::inputs![
379            "input_ids" => Value::from_array(self.input_ids.clone())?,
380            "attention_mask" => Value::from_array(self.attention_mask.clone())?,
381        ];
382        if need_token_type_ids {
383            let token_type_ids = std::mem::take(&mut self.token_type_ids);
384            inputs.push((
385                "token_type_ids".into(),
386                Value::from_array(token_type_ids)?.into(),
387            ));
388        }
389        Ok(inputs)
390    }
391}
392
393/// Tokenize a batch into padded `[batch, sequence]` tensors.
394#[cfg(feature = "onnx")]
395pub(crate) fn encode_batch<'s, E>(tokenizer: &Tokenizer, inputs: Vec<E>) -> Result<EncodedBatch>
396where
397    E: Into<EncodeInput<'s>> + Send,
398{
399    let encodings = tokenizer
400        .encode_batch(inputs, true)
401        .map_err(|e| Error::Tokenization(format!("Failed to encode the batch: {e}")))?;
402    encodings_to_batch(&encodings)
403}
404
405#[cfg(feature = "onnx")]
406fn encodings_to_batch(encodings: &[Encoding]) -> Result<EncodedBatch> {
407    let encoding_length = encodings.first().ok_or(Error::EmptyTokenizations)?.len();
408    let batch_size = encodings.len();
409    let max_size = encoding_length * batch_size;
410
411    let mut ids = Vec::with_capacity(max_size);
412    let mut mask = Vec::with_capacity(max_size);
413    let mut type_ids = Vec::with_capacity(max_size);
414    for encoding in encodings {
415        ids.extend(encoding.get_ids().iter().map(|&x| x as i64));
416        mask.extend(encoding.get_attention_mask().iter().map(|&x| x as i64));
417        type_ids.extend(encoding.get_type_ids().iter().map(|&x| x as i64));
418    }
419
420    let shape = (batch_size, encoding_length);
421    let to_array = |data: Vec<i64>| {
422        Array2::from_shape_vec(shape, data).map_err(|e| Error::InvalidShape(e.to_string()))
423    };
424    Ok(EncodedBatch {
425        input_ids: to_array(ids)?,
426        attention_mask: to_array(mask)?,
427        token_type_ids: to_array(type_ids)?,
428    })
429}
430
431#[cfg(feature = "onnx")]
432fn default_environment() -> Result<Environment> {
433    static DEFAULT: Mutex<Option<Environment>> = Mutex::new(None);
434    let mut default = DEFAULT.lock().unwrap_or_else(PoisonError::into_inner);
435    if let Some(environment) = default.as_ref() {
436        return Ok(environment.clone());
437    }
438    let environment = ort::init().build().map_err(|e| {
439        if e.message().contains("only one environment") {
440            Error::EnvironmentRequired
441        } else {
442            Error::Ort(e)
443        }
444    })?;
445    *default = Some(environment.clone());
446    Ok(environment)
447}
448
449#[cfg(feature = "onnx")]
450pub(crate) fn init_session_builder(
451    environment: Option<Environment>,
452    execution_providers: Vec<ExecutionProviderDispatch>,
453    intra_threads: Option<usize>,
454    session_config: Vec<(String, String)>,
455) -> Result<SessionBuilder> {
456    let threads = match intra_threads {
457        Some(n) => n,
458        None => std::thread::available_parallelism()?.get(),
459    };
460
461    #[cfg(feature = "directml")]
462    let has_directml = execution_providers
463        .iter()
464        .any(|ep| ep.name() == <ort::ep::DirectML as ort::ep::ExecutionProvider>::NAME);
465    #[cfg(not(feature = "directml"))]
466    let has_directml = false;
467
468    let builder_error = |err: ort::Error<SessionBuilder>| Error::OrtBuilder(err.to_string());
469
470    let environment = match environment {
471        Some(environment) => environment,
472        None => default_environment()?,
473    };
474
475    let mut builder = ort::session::Session::builder(&environment)?
476        .with_execution_providers(execution_providers)
477        .map_err(builder_error)?
478        .with_optimization_level(GraphOptimizationLevel::Level3)
479        .map_err(builder_error)?
480        .with_intra_threads(threads)
481        .map_err(builder_error)?;
482
483    for (key, value) in session_config {
484        builder = builder
485            .with_config_entry(&key, &value)
486            .map_err(builder_error)?;
487    }
488
489    if has_directml {
490        builder = builder
491            .with_memory_pattern(false)
492            .map_err(builder_error)?
493            .with_parallel_execution(false)
494            .map_err(builder_error)?;
495    }
496
497    Ok(builder)
498}
499
500#[cfg(all(test, feature = "onnx"))]
501mod tests {
502    use super::*;
503
504    fn minimal_tokenizer_bytes() -> Vec<u8> {
505        // Minimal valid tokenizer.json (word-level model with a tiny vocab).
506        br#"{
507            "version": "1.0",
508            "truncation": null,
509            "padding": null,
510            "added_tokens": [],
511            "normalizer": null,
512            "pre_tokenizer": {"type": "Whitespace"},
513            "post_processor": null,
514            "decoder": null,
515            "model": {
516                "type": "WordLevel",
517                "unk_token": "[UNK]",
518                "vocab": {"[UNK]": 0, "[PAD]": 1, "hello": 2}
519            }
520        }"#
521        .to_vec()
522    }
523
524    fn tokenizer_files(tokenizer_config: &str) -> TokenizerFiles {
525        TokenizerFiles {
526            tokenizer_file: minimal_tokenizer_bytes(),
527            config_file: br#"{"pad_token_id": 0}"#.to_vec(),
528            special_tokens_map_file: b"{}".to_vec(),
529            tokenizer_config_file: tokenizer_config.as_bytes().to_vec(),
530        }
531    }
532
533    #[test]
534    fn load_tokenizer_ok_with_complete_config() {
535        let files = tokenizer_files(r#"{"model_max_length": 512, "pad_token": "[PAD]"}"#);
536        assert!(load_tokenizer(files, 512).is_ok());
537    }
538
539    #[test]
540    fn load_tokenizer_errors_on_missing_pad_token() {
541        let files = tokenizer_files(r#"{"model_max_length": 512}"#);
542        let err = load_tokenizer(files, 512).unwrap_err();
543        assert!(
544            err.to_string().contains("pad_token"),
545            "error message was: {err}"
546        );
547    }
548
549    #[test]
550    fn load_tokenizer_errors_on_missing_model_max_length() {
551        let files = tokenizer_files(r#"{"pad_token": "[PAD]"}"#);
552        let err = load_tokenizer(files, 512).unwrap_err();
553        assert!(
554            err.to_string().contains("model_max_length"),
555            "error message was: {err}"
556        );
557    }
558    #[test]
559    fn load_tokenizer_accepts_added_token_object_as_pad_token() {
560        let files = tokenizer_files(
561            r#"{"model_max_length": 512, "pad_token": {"__type": "AddedToken", "content": "[PAD]", "lstrip": false}}"#,
562        );
563        let tokenizer = load_tokenizer(files, 512).unwrap();
564        assert_eq!(tokenizer.get_padding().unwrap().pad_token, "[PAD]");
565    }
566
567    #[test]
568    fn load_tokenizer_resolves_pad_id_from_vocab_when_config_lacks_it() {
569        let mut files = tokenizer_files(r#"{"model_max_length": 512, "pad_token": "[PAD]"}"#);
570        files.config_file = b"{}".to_vec();
571        let tokenizer = load_tokenizer(files, 512).unwrap();
572        assert_eq!(tokenizer.get_padding().unwrap().pad_id, 1);
573    }
574
575    #[test]
576    fn encode_batch_pads_to_longest_and_masks_padding() {
577        let files = tokenizer_files(r#"{"model_max_length": 512, "pad_token": "[PAD]"}"#);
578        let tokenizer = load_tokenizer(files, 512).unwrap();
579        let batch = encode_batch(&tokenizer, vec!["hello", "hello hello"]).unwrap();
580        assert_eq!(batch.input_ids.dim(), (2, 2));
581        assert_eq!(batch.attention_mask.row(0).to_vec(), vec![1, 0]);
582        assert_eq!(batch.attention_mask.row(1).to_vec(), vec![1, 1]);
583        assert_eq!(batch.input_ids[[0, 1]], 0);
584        assert_eq!(batch.input_ids.row(1).to_vec(), vec![2, 2]);
585        assert!(encode_batch::<&str>(&tokenizer, vec![]).is_err());
586    }
587
588    #[test]
589    fn init_session_builder_applies_config_entry() {
590        let builder = init_session_builder(
591            None,
592            vec![],
593            Some(1),
594            vec![("session.disable_prepacking".into(), "1".into())],
595        );
596        assert!(builder.is_ok());
597    }
598
599    #[test]
600    fn init_session_builder_shares_one_default_environment() {
601        let first = init_session_builder(None, vec![], Some(1), vec![]);
602        let second = init_session_builder(None, vec![], Some(1), vec![]);
603        assert!(first.is_ok() && second.is_ok());
604    }
605}