Skip to main content

memory/
embed.rs

1//! Embedders: text to vectors, for a provider that can recall by meaning
2//! as well as by words. None is used unless the settings name one.
3//!
4//! - [`StaticVectors`]: a table of word vectors read from a file (the
5//!   word2vec text format that fastText and GloVe use, and that a
6//!   model2vec model can be exported to). A text's vector is the mean of
7//!   its words' vectors. No model runs and nothing leaves the machine.
8//! - [`Command`]: a program the user names that runs a local model. It
9//!   reads a JSON array of texts on standard input and writes a JSON array
10//!   of vectors, one per text, on standard output.
11//!
12//! Vectors from different models are never compared: each embedder names
13//! its [`model`](Embedder::model), and a provider keeps that name beside
14//! every vector it stores.
15
16use std::collections::HashMap;
17use std::io::Write as _;
18use std::path::{Path, PathBuf};
19use std::process::Stdio;
20use std::time::Duration;
21
22use crate::Error;
23use crate::search::words;
24
25/// Turns texts into vectors of one dimension.
26pub trait Embedder: Send + Sync + std::fmt::Debug {
27    /// Names the model, so vectors from another one are never compared
28    /// with these: `static:<file name>` or `local:<program>`.
29    fn model(&self) -> &str;
30
31    /// One vector per text, in order, each [`dimension`](Self::dimension)
32    /// long. A text the model has nothing for gets zeros.
33    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, Error>;
34
35    fn dimension(&self) -> usize;
36}
37
38/// Cosine similarity, or 0 when either vector is all zeros.
39pub fn cosine(a: &[f32], b: &[f32]) -> f32 {
40    let (mut dot, mut na, mut nb) = (0f32, 0f32, 0f32);
41    for (x, y) in a.iter().zip(b) {
42        dot += x * y;
43        na += x * x;
44        nb += y * y;
45    }
46    if na == 0.0 || nb == 0.0 {
47        0.0
48    } else {
49        dot / (na.sqrt() * nb.sqrt())
50    }
51}
52
53/// Word vectors from a file.
54#[derive(Debug)]
55pub struct StaticVectors {
56    model: String,
57    dimension: usize,
58    words: HashMap<String, Vec<f32>>,
59}
60
61/// The largest vector file read, so a wrong path cannot fill memory.
62const MAX_FILE: u64 = 1 << 30;
63
64impl StaticVectors {
65    /// Read `path`: one word per line followed by its numbers, separated
66    /// by spaces; a first line of two numbers (count, dimension) is a
67    /// header and skipped. Words are matched in lower case.
68    pub fn load(path: &Path) -> Result<StaticVectors, Error> {
69        let io = |e: std::io::Error| Error::Io(format!("{}: {e}", path.display()));
70        let size = std::fs::metadata(path).map_err(io)?.len();
71        if size > MAX_FILE {
72            return Err(Error::Invalid(format!(
73                "{}: {size} bytes is more than a vector file may hold",
74                path.display()
75            )));
76        }
77        let text = std::fs::read_to_string(path).map_err(io)?;
78        let name = path
79            .file_name()
80            .map(|n| n.to_string_lossy().into_owned())
81            .unwrap_or_default();
82        StaticVectors::parse(&format!("static:{name}"), &text)
83            .map_err(|m| Error::Invalid(format!("{}: {m}", path.display())))
84    }
85
86    /// The same as [`load`](Self::load), from text.
87    pub fn parse(model: &str, text: &str) -> Result<StaticVectors, String> {
88        let mut words = HashMap::new();
89        let mut dimension = 0;
90        for (i, line) in text.lines().enumerate() {
91            let mut parts = line.split_whitespace();
92            let Some(word) = parts.next() else { continue };
93            let numbers: Result<Vec<f32>, _> = parts.map(str::parse::<f32>).collect();
94            let Ok(v) = numbers else {
95                return Err(format!("line {}: not a word and its numbers", i + 1));
96            };
97            if i == 0 && v.len() == 1 && word.parse::<u64>().is_ok() {
98                continue;
99            }
100            if v.is_empty() {
101                return Err(format!("line {}: `{word}` has no numbers", i + 1));
102            }
103            if dimension == 0 {
104                dimension = v.len();
105            } else if v.len() != dimension {
106                return Err(format!(
107                    "line {}: `{word}` has {} numbers, the others {dimension}",
108                    i + 1,
109                    v.len()
110                ));
111            }
112            words.entry(word.to_lowercase()).or_insert(v);
113        }
114        if words.is_empty() {
115            return Err("no word vectors".into());
116        }
117        Ok(StaticVectors {
118            model: model.to_owned(),
119            dimension,
120            words,
121        })
122    }
123}
124
125impl Embedder for StaticVectors {
126    fn model(&self) -> &str {
127        &self.model
128    }
129
130    fn dimension(&self) -> usize {
131        self.dimension
132    }
133
134    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, Error> {
135        Ok(texts
136            .iter()
137            .map(|t| {
138                let mut sum = vec![0f32; self.dimension];
139                let mut n = 0u32;
140                for w in words(t) {
141                    if let Some(v) = self.words.get(&w) {
142                        for (s, x) in sum.iter_mut().zip(v) {
143                            *s += x;
144                        }
145                        n += 1;
146                    }
147                }
148                if n > 0 {
149                    for s in &mut sum {
150                        *s /= n as f32;
151                    }
152                }
153                sum
154            })
155            .collect())
156    }
157}
158
159/// An embedder made on first use, so a large vector file is read when
160/// memory is first asked for, off the daemon's event loop, and not when
161/// the settings are read. A failure to make it is kept and returned by
162/// every call.
163pub struct Lazy {
164    model: String,
165    make: Box<dyn Fn() -> Result<Box<dyn Embedder>, Error> + Send + Sync>,
166    made: std::sync::OnceLock<Result<Box<dyn Embedder>, Error>>,
167}
168
169impl std::fmt::Debug for Lazy {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.debug_struct("Lazy")
172            .field("model", &self.model)
173            .finish_non_exhaustive()
174    }
175}
176
177impl Lazy {
178    /// `model` must be the name the made embedder gives.
179    pub fn new(
180        model: String,
181        make: impl Fn() -> Result<Box<dyn Embedder>, Error> + Send + Sync + 'static,
182    ) -> Lazy {
183        Lazy {
184            model,
185            make: Box::new(make),
186            made: std::sync::OnceLock::new(),
187        }
188    }
189
190    /// Word vectors from `path`, read on first use.
191    pub fn static_vectors(path: PathBuf) -> Lazy {
192        let name = path
193            .file_name()
194            .map(|n| n.to_string_lossy().into_owned())
195            .unwrap_or_default();
196        Lazy::new(format!("static:{name}"), move || {
197            StaticVectors::load(&path).map(|v| Box::new(v) as Box<dyn Embedder>)
198        })
199    }
200
201    fn get(&self) -> Result<&dyn Embedder, Error> {
202        match self.made.get_or_init(|| (self.make)()) {
203            Ok(e) => Ok(e.as_ref()),
204            Err(e) => Err(e.clone()),
205        }
206    }
207}
208
209impl Embedder for Lazy {
210    fn model(&self) -> &str {
211        &self.model
212    }
213
214    fn dimension(&self) -> usize {
215        self.get().map_or(0, Embedder::dimension)
216    }
217
218    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, Error> {
219        self.get()?.embed(texts)
220    }
221}
222
223/// A local model behind a program: `argv[0]` with the rest as arguments,
224/// run once per call. It gets a JSON array of strings on standard input
225/// and must print a JSON array of number arrays, one per string, all
226/// `dimension` long, and exit 0 within the timeout.
227#[derive(Debug)]
228pub struct Command {
229    model: String,
230    argv: Vec<String>,
231    dimension: usize,
232    timeout: Duration,
233}
234
235impl Command {
236    pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
237
238    pub fn new(argv: Vec<String>, dimension: usize, timeout: Duration) -> Result<Command, Error> {
239        let program = argv
240            .first()
241            .filter(|p| !p.trim().is_empty())
242            .ok_or_else(|| Error::Invalid("a local embedder needs a command".into()))?;
243        if dimension == 0 {
244            return Err(Error::Invalid(
245                "a local embedder needs its dimension".into(),
246            ));
247        }
248        let name = PathBuf::from(program)
249            .file_name()
250            .map(|n| n.to_string_lossy().into_owned())
251            .unwrap_or_else(|| program.clone());
252        Ok(Command {
253            model: format!("local:{name}"),
254            argv,
255            dimension,
256            timeout,
257        })
258    }
259}
260
261impl Embedder for Command {
262    fn model(&self) -> &str {
263        &self.model
264    }
265
266    fn dimension(&self) -> usize {
267        self.dimension
268    }
269
270    fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>, Error> {
271        if texts.is_empty() {
272            return Ok(Vec::new());
273        }
274        let fail = |m: String| Error::Io(format!("embedder `{}`: {m}", self.argv[0]));
275        let input = serde_json::to_vec(texts).map_err(|e| fail(e.to_string()))?;
276        let mut child = std::process::Command::new(&self.argv[0])
277            .args(&self.argv[1..])
278            .stdin(Stdio::piped())
279            .stdout(Stdio::piped())
280            .stderr(Stdio::null())
281            .spawn()
282            .map_err(|e| fail(e.to_string()))?;
283        // Written from a thread, so a program that prints before it has
284        // read everything cannot dead-lock with us.
285        let mut stdin = child.stdin.take().ok_or_else(|| fail("no stdin".into()))?;
286        let writer = std::thread::spawn(move || {
287            let _ = stdin.write_all(&input);
288        });
289        let mut stdout = child
290            .stdout
291            .take()
292            .ok_or_else(|| fail("no stdout".into()))?;
293        let (tx, rx) = std::sync::mpsc::channel();
294        std::thread::spawn(move || {
295            let mut out = Vec::new();
296            let r = std::io::Read::read_to_end(&mut stdout, &mut out).map(|_| out);
297            let _ = tx.send(r);
298        });
299        let out = match rx.recv_timeout(self.timeout) {
300            Ok(r) => r.map_err(|e| fail(e.to_string()))?,
301            Err(_) => {
302                let _ = child.kill();
303                let _ = child.wait();
304                return Err(fail(format!("no answer within {:?}", self.timeout)));
305            }
306        };
307        let _ = writer.join();
308        let status = child.wait().map_err(|e| fail(e.to_string()))?;
309        if !status.success() {
310            return Err(fail(format!("exited with {status}")));
311        }
312        let vectors: Vec<Vec<f32>> =
313            serde_json::from_slice(&out).map_err(|e| fail(format!("its answer: {e}")))?;
314        if vectors.len() != texts.len() || vectors.iter().any(|v| v.len() != self.dimension) {
315            return Err(fail(format!(
316                "expected {} vectors of {} numbers",
317                texts.len(),
318                self.dimension
319            )));
320        }
321        Ok(vectors)
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn static_vectors_average_the_words_they_know() {
331        let v = StaticVectors::parse("static:t", "3 2\ntabs 1 0\nSpaces 0 1\nindent 1 1\n")
332            .expect("parse");
333        assert_eq!(v.dimension(), 2);
334        let got = v
335            .embed(&["Tabs and spaces", "nothing known", ""])
336            .expect("embed");
337        assert_eq!(got, vec![vec![0.5, 0.5], vec![0.0, 0.0], vec![0.0, 0.0]]);
338        assert!((cosine(&got[0], &[1.0, 1.0]) - 1.0).abs() < 1e-6);
339        assert_eq!(cosine(&got[1], &[1.0, 1.0]), 0.0);
340        assert!(StaticVectors::parse("m", "a 1 2\nb 1\n").is_err());
341        assert!(StaticVectors::parse("m", "a x\n").is_err());
342        assert!(StaticVectors::parse("m", "").is_err());
343    }
344
345    #[test]
346    fn a_lazy_embedder_reads_its_file_on_first_use() {
347        let dir = std::env::temp_dir().join(format!("dreamer-embed-{}", std::process::id()));
348        let _ = std::fs::remove_dir_all(&dir);
349        std::fs::create_dir_all(&dir).expect("dir");
350        let path = dir.join("words.vec");
351        let lazy = Lazy::static_vectors(path.clone());
352        assert_eq!(lazy.model(), "static:words.vec");
353        // Written after the embedder was made: nothing was read yet.
354        std::fs::write(&path, "tabs 1 0\n").expect("write");
355        assert_eq!(lazy.dimension(), 2);
356        assert_eq!(lazy.embed(&["tabs"]).expect("embed"), vec![vec![1.0, 0.0]]);
357        let missing = Lazy::static_vectors(dir.join("none.vec"));
358        assert!(missing.embed(&["tabs"]).is_err());
359        assert_eq!(missing.dimension(), 0);
360        let _ = std::fs::remove_dir_all(&dir);
361    }
362
363    #[test]
364    fn a_command_embedder_speaks_json_and_is_checked() {
365        let sh = |script: &str, dim| {
366            Command::new(
367                vec!["sh".into(), "-c".into(), script.into()],
368                dim,
369                Duration::from_secs(10),
370            )
371            .expect("command")
372        };
373        let ok = sh("cat >/dev/null; printf '[[1,0],[0,1]]'", 2);
374        assert_eq!(ok.model(), "local:sh");
375        assert_eq!(
376            ok.embed(&["a", "b"]).expect("embed"),
377            vec![vec![1.0, 0.0], vec![0.0, 1.0]]
378        );
379        assert!(
380            sh("cat >/dev/null; printf '[[1,0]]'", 2)
381                .embed(&["a", "b"])
382                .is_err()
383        );
384        assert!(sh("cat >/dev/null; exit 3", 2).embed(&["a"]).is_err());
385        assert!(Command::new(vec![], 2, Duration::from_secs(1)).is_err());
386    }
387}