Skip to main content

aidaemon_memory/
embed.rs

1//! Text embedders: the [`Embedder`] extension point, a deterministic
2//! offline [`HashEmbedder`], and (feature `fastembed`) a local ONNX model.
3
4use async_trait::async_trait;
5
6use crate::error::{MemoryError, Result};
7use crate::scoring::tokens;
8
9/// Turns text into vectors. Implement this to use an embedding API or
10/// another local model; [`crate::Memory`] only sees `Arc<dyn Embedder>`.
11///
12/// Vectors should be L2-normalized so cosine similarity is a dot product,
13/// but [`cosine`] normalizes anyway.
14#[async_trait]
15pub trait Embedder: Send + Sync {
16    /// Stable identifier persisted beside every vector. Changing the model
17    /// changes this id, and old vectors are then ignored (lexical recall
18    /// still works) instead of being compared across models, until
19    /// [`crate::Memory::reembed_batch`] replaces them.
20    fn model_id(&self) -> &str;
21
22    /// Length of every returned vector.
23    fn dimensions(&self) -> usize;
24
25    /// One vector per input text, in order.
26    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>>;
27}
28
29#[async_trait]
30impl<E: Embedder + ?Sized> Embedder for std::sync::Arc<E> {
31    fn model_id(&self) -> &str {
32        (**self).model_id()
33    }
34    fn dimensions(&self) -> usize {
35        (**self).dimensions()
36    }
37    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
38        (**self).embed(texts).await
39    }
40}
41
42/// Cosine similarity; 0.0 for mismatched lengths or zero vectors.
43pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
44    if a.len() != b.len() || a.is_empty() {
45        return 0.0;
46    }
47    let (mut dot, mut na, mut nb) = (0.0f32, 0.0f32, 0.0f32);
48    for (x, y) in a.iter().zip(b) {
49        dot += x * y;
50        na += x * x;
51        nb += y * y;
52    }
53    if na <= f32::EPSILON || nb <= f32::EPSILON {
54        return 0.0;
55    }
56    dot / (na.sqrt() * nb.sqrt())
57}
58
59/// Little-endian f32 bytes, the BLOB format used by `SqliteMemoryStore`.
60pub fn encode_embedding(vector: &[f32]) -> Vec<u8> {
61    vector.iter().flat_map(|v| v.to_le_bytes()).collect()
62}
63
64/// Inverse of [`encode_embedding`]; `None` for a malformed blob.
65pub fn decode_embedding(bytes: &[u8]) -> Option<Vec<f32>> {
66    if !bytes.len().is_multiple_of(4) {
67        return None;
68    }
69    let (chunks, _) = bytes.as_chunks::<4>();
70    Some(chunks.iter().map(|c| f32::from_le_bytes(*c)).collect())
71}
72
73/// Decode a stored vector that must have `dims` dimensions. Besides the
74/// binary format of [`encode_embedding`], this reads the legacy format a
75/// JSON array of numbers (older daemon databases stored vectors that way).
76/// Any other blob, including binary of the wrong length, is an error.
77pub fn decode_embedding_with_dim(bytes: &[u8], dims: usize) -> Result<Vec<f32>> {
78    let binary_len = dims
79        .checked_mul(std::mem::size_of::<f32>())
80        .ok_or_else(|| MemoryError::Invalid("embedding dimension overflow".into()))?;
81    if dims > 0 && bytes.len() == binary_len {
82        return Ok(decode_embedding(bytes).unwrap_or_default());
83    }
84    if bytes.first() == Some(&b'[') {
85        return serde_json::from_slice(bytes)
86            .map_err(|e| MemoryError::Invalid(format!("legacy JSON embedding: {e}")));
87    }
88    Err(MemoryError::Invalid(format!(
89        "unknown embedding format: length {}, expected {dims} dimensions, first byte {:?}",
90        bytes.len(),
91        bytes.first()
92    )))
93}
94
95/// Deterministic hashed bag-of-words embedder. No model, no network, same
96/// output on every machine (FNV-1a hashing). Similarity reflects shared
97/// words only, so it suits tests and offline use, not production recall.
98#[derive(Debug, Clone)]
99pub struct HashEmbedder {
100    dims: usize,
101    id: String,
102}
103
104impl HashEmbedder {
105    pub fn new(dims: usize) -> Self {
106        let dims = dims.max(8);
107        Self {
108            dims,
109            id: format!("hash-bow-v1/{dims}"),
110        }
111    }
112
113    /// Embed one text synchronously.
114    pub fn embed_one(&self, text: &str) -> Vec<f32> {
115        let mut v = vec![0.0f32; self.dims];
116        for token in tokens(text) {
117            let h = fnv1a(token.as_bytes());
118            let index = (h % self.dims as u64) as usize;
119            let sign = if (h >> 63) == 0 { 1.0 } else { -1.0 };
120            v[index] += sign;
121        }
122        let norm = v.iter().map(|x| x * x).sum::<f32>().sqrt();
123        if norm > 0.0 {
124            v.iter_mut().for_each(|x| *x /= norm);
125        }
126        v
127    }
128}
129
130impl Default for HashEmbedder {
131    fn default() -> Self {
132        Self::new(256)
133    }
134}
135
136fn fnv1a(bytes: &[u8]) -> u64 {
137    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
138    for b in bytes {
139        hash ^= u64::from(*b);
140        hash = hash.wrapping_mul(0x0100_0000_01b3);
141    }
142    hash
143}
144
145#[async_trait]
146impl Embedder for HashEmbedder {
147    fn model_id(&self) -> &str {
148        &self.id
149    }
150
151    fn dimensions(&self) -> usize {
152        self.dims
153    }
154
155    async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
156        Ok(texts.iter().map(|t| self.embed_one(t)).collect())
157    }
158}
159
160#[cfg(feature = "fastembed")]
161pub use fast::{DEFAULT_FASTEMBED_MODEL, FastEmbedder};
162
163#[cfg(feature = "fastembed")]
164mod fast {
165    use std::path::PathBuf;
166    use std::sync::{Arc, Mutex};
167
168    use async_trait::async_trait;
169    use fastembed::{AutoDevicePolicy, EmbeddingModel, TextEmbedding, TextInitOptions};
170    use tokio::sync::OnceCell;
171
172    use super::Embedder;
173    use crate::error::{MemoryError, Result};
174
175    /// The model [`FastEmbedder::new`] runs: AllMiniLM-L6-v2, 384
176    /// dimensions.
177    pub const DEFAULT_FASTEMBED_MODEL: &str = "AllMiniLML6V2";
178
179    /// The id vectors of AllMiniLM-L6-v2 have always been stored under.
180    const LEGACY_MINILM_ID: &str = "fastembed/all-MiniLM-L6-v2";
181
182    /// A local ONNX text-embedding model via fastembed. The model is
183    /// downloaded and loaded lazily on the first `embed` call; loading and
184    /// inference run on `spawn_blocking`.
185    pub struct FastEmbedder {
186        choice: EmbeddingModel,
187        model_id: String,
188        dimensions: usize,
189        cache_dir: Option<PathBuf>,
190        show_download_progress: bool,
191        // fastembed's `embed` takes `&mut self`: one call at a time.
192        model: OnceCell<Arc<Mutex<TextEmbedding>>>,
193    }
194
195    impl FastEmbedder {
196        /// AllMiniLM-L6-v2 ([`DEFAULT_FASTEMBED_MODEL`]).
197        pub fn new() -> Self {
198            Self::named(DEFAULT_FASTEMBED_MODEL).expect("the default model is supported")
199        }
200
201        /// Any text model fastembed supports, by its `EmbeddingModel`
202        /// variant name, case-insensitive: `"AllMiniLML6V2Q"`,
203        /// `"BGESmallENV15"`, `"ParaphraseMLMiniLML12V2"`, ...
204        pub fn named(name: &str) -> Result<Self> {
205            let choice: EmbeddingModel = name.trim().parse().map_err(|_| {
206                MemoryError::Embedding(format!(
207                    "unknown embedding model `{name}`; supported: {}",
208                    Self::supported().join(", ")
209                ))
210            })?;
211            let dimensions = TextEmbedding::get_model_info(&choice)
212                .map_err(|e| MemoryError::Embedding(e.to_string()))?
213                .dim;
214            let model_id = if choice == EmbeddingModel::AllMiniLML6V2 {
215                LEGACY_MINILM_ID.to_string()
216            } else {
217                format!("fastembed/{choice:?}")
218            };
219            Ok(Self {
220                choice,
221                model_id,
222                dimensions,
223                cache_dir: None,
224                show_download_progress: false,
225                model: OnceCell::new(),
226            })
227        }
228
229        /// The names [`FastEmbedder::named`] accepts.
230        pub fn supported() -> Vec<String> {
231            TextEmbedding::list_supported_models()
232                .into_iter()
233                .map(|info| format!("{:?}", info.model))
234                .collect()
235        }
236
237        /// Where model files are cached (fastembed's default otherwise).
238        pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
239            self.cache_dir = Some(dir.into());
240            self
241        }
242
243        pub fn show_download_progress(mut self, show: bool) -> Self {
244            self.show_download_progress = show;
245            self
246        }
247
248        async fn model(&self) -> Result<Arc<Mutex<TextEmbedding>>> {
249            let choice = self.choice.clone();
250            let cache_dir = self.cache_dir.clone();
251            let progress = self.show_download_progress;
252            self.model
253                .get_or_try_init(|| async move {
254                    tokio::task::spawn_blocking(move || {
255                        let mut options =
256                            TextInitOptions::new(choice).with_show_download_progress(progress);
257                        // Plain CPU: ort's default registers CoreML on macOS,
258                        // which costs ~5x the memory for this model and is slower.
259                        options.auto_device = Some(AutoDevicePolicy::PreferCPU);
260                        if let Some(dir) = cache_dir {
261                            options = options.with_cache_dir(dir);
262                        }
263                        TextEmbedding::try_new(options)
264                            .map(|model| Arc::new(Mutex::new(model)))
265                            .map_err(|e| MemoryError::Embedding(e.to_string()))
266                    })
267                    .await
268                    .map_err(|e| MemoryError::Embedding(e.to_string()))?
269                })
270                .await
271                .cloned()
272        }
273    }
274
275    impl Default for FastEmbedder {
276        fn default() -> Self {
277            Self::new()
278        }
279    }
280
281    #[async_trait]
282    impl Embedder for FastEmbedder {
283        fn model_id(&self) -> &str {
284            &self.model_id
285        }
286
287        fn dimensions(&self) -> usize {
288            self.dimensions
289        }
290
291        async fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
292            if texts.is_empty() {
293                return Ok(Vec::new());
294            }
295            let model = self.model().await?;
296            let texts = texts.to_vec();
297            tokio::task::spawn_blocking(move || {
298                let mut model = model.lock().map_err(|e| {
299                    MemoryError::Embedding(format!("embedding model lock poisoned: {e}"))
300                })?;
301                model
302                    .embed(texts, None)
303                    .map_err(|e| MemoryError::Embedding(e.to_string()))
304            })
305            .await
306            .map_err(|e| MemoryError::Embedding(e.to_string()))?
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::{decode_embedding_with_dim, encode_embedding};
314
315    #[test]
316    fn dimensioned_decode_reads_binary_and_legacy_json() {
317        let original: Vec<f32> = (0..384).map(|i| i as f32 * 0.001).collect();
318        let binary = encode_embedding(&original);
319        assert_eq!(binary.len(), 1536);
320        assert_eq!(decode_embedding_with_dim(&binary, 384).unwrap(), original);
321        let json = serde_json::to_vec(&original).unwrap();
322        assert_eq!(decode_embedding_with_dim(&json, 384).unwrap(), original);
323    }
324
325    #[test]
326    fn dimensioned_decode_rejects_other_blobs() {
327        assert!(decode_embedding_with_dim(&[0u8; 100], 384).is_err());
328        assert!(decode_embedding_with_dim(&[], 384).is_err());
329        // Binary of another model's dimension is not silently accepted.
330        assert!(decode_embedding_with_dim(&encode_embedding(&[1.0; 8]), 384).is_err());
331    }
332
333    #[test]
334    fn special_float_values_round_trip() {
335        let mut vector: Vec<f32> = (0..384).map(|i| i as f32).collect();
336        vector[0] = f32::NEG_INFINITY;
337        vector[1] = f32::INFINITY;
338        vector[3] = -0.0;
339        let decoded = decode_embedding_with_dim(&encode_embedding(&vector), 384).unwrap();
340        assert!(decoded[0].is_infinite() && decoded[0].is_sign_negative());
341        assert!(decoded[1].is_infinite() && decoded[1].is_sign_positive());
342    }
343
344    use super::*;
345
346    #[tokio::test]
347    async fn hash_embedder_is_deterministic_and_normalized() {
348        let a = HashEmbedder::new(128);
349        let b = HashEmbedder::new(128);
350        let texts = vec!["Alice Rivera likes hiking".to_string()];
351        let va = a.embed(&texts).await.unwrap();
352        let vb = b.embed(&texts).await.unwrap();
353        assert_eq!(va, vb);
354        assert_eq!(va[0].len(), 128);
355        let norm: f32 = va[0].iter().map(|x| x * x).sum::<f32>().sqrt();
356        assert!((norm - 1.0).abs() < 1e-5);
357        let related = a.embed_one("hiking trips for Alice");
358        let unrelated = a.embed_one("quarterly invoice totals");
359        assert!(cosine(&va[0], &related) > cosine(&va[0], &unrelated));
360        assert_eq!(a.embed_one(""), vec![0.0; 128]);
361    }
362
363    #[test]
364    fn blobs_round_trip() {
365        let v = vec![0.25f32, -1.5, 3.0];
366        assert_eq!(decode_embedding(&encode_embedding(&v)), Some(v));
367        assert_eq!(decode_embedding(&[1, 2, 3]), None);
368    }
369
370    #[cfg(feature = "fastembed")]
371    #[tokio::test]
372    #[ignore = "downloads the AllMiniLM-L6-v2 model"]
373    async fn fastembed_embeds_with_384_dims() {
374        let e = FastEmbedder::new();
375        let out = e.embed(&["Mia and Zoe".to_string()]).await.unwrap();
376        assert_eq!(out[0].len(), 384);
377    }
378
379    #[cfg(feature = "fastembed")]
380    #[test]
381    fn models_are_chosen_by_name_with_their_own_id_and_dimensions() {
382        let default = FastEmbedder::new();
383        assert_eq!(default.model_id(), "fastembed/all-MiniLM-L6-v2");
384        assert_eq!(default.dimensions(), 384);
385
386        let quantized = FastEmbedder::named("allminilml6v2q").unwrap();
387        assert_eq!(quantized.model_id(), "fastembed/AllMiniLML6V2Q");
388        assert_eq!(quantized.dimensions(), 384);
389
390        assert_eq!(
391            FastEmbedder::named("BGEBaseENV15").unwrap().dimensions(),
392            768
393        );
394        let unknown = FastEmbedder::named("no-such-model")
395            .err()
396            .unwrap()
397            .to_string();
398        assert!(unknown.contains("AllMiniLML6V2Q"), "{unknown}");
399    }
400}