Skip to main content

rig_llama_cpp/
embedding.rs

1use std::num::NonZeroU32;
2use std::thread;
3
4use rig_core::driver::{Exchange, Local, Opened, Opening, Step, Transport};
5use rig_core::embeddings::{Embedding, EmbeddingResponse};
6use rig_core::error::ProviderError;
7use rig_core::operation::Embedding as EmbeddingOp;
8use rig_core::wire::Capabilities;
9use tokio::sync::{mpsc, oneshot};
10
11use crate::error::LoadError;
12
13/// The most texts one embedding request takes.
14const MAX_DOCUMENTS: usize = 256;
15
16enum EmbeddingCommand {
17    Request(EmbeddingRequest),
18    Shutdown,
19}
20
21struct EmbeddingRequest {
22    texts: Vec<String>,
23    response_tx: oneshot::Sender<Result<Vec<Vec<f32>>, String>>,
24}
25
26/// The llama.cpp embedding client.
27///
28/// `EmbeddingClient` loads a GGUF embedding model on a dedicated worker thread
29/// and exposes it as a Rig embedding [`Model`](rig_core::Model) (see
30/// [`EmbeddingModelHandle`]). Create one with [`EmbeddingClient::from_gguf`].
31///
32/// ```rust,no_run
33/// # #[tokio::main]
34/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
35/// let client = rig_llama_cpp::EmbeddingClient::from_gguf(
36///     "path/to/embedding-model.gguf",
37///     99,   // n_gpu_layers
38///     8192, // n_ctx
39/// )?;
40/// let model = client.embedding_model("local");
41/// let embedding = model.embed_text("Hello, world!").await?;
42/// println!("dims: {}", embedding.vec.len());
43/// # Ok(())
44/// # }
45/// ```
46pub struct EmbeddingClient {
47    request_tx: mpsc::UnboundedSender<EmbeddingCommand>,
48    ndims: usize,
49    worker_handle: Option<thread::JoinHandle<()>>,
50}
51
52impl EmbeddingClient {
53    /// Load a GGUF embedding model and start the embedding worker thread.
54    ///
55    /// # Arguments
56    ///
57    /// * `model_path` — Path to a `.gguf` embedding model file.
58    /// * `n_gpu_layers` — Number of layers to offload to the GPU (`u32::MAX` for all).
59    /// * `n_ctx` — Context window size in tokens.
60    ///
61    /// # Errors
62    ///
63    /// Returns a [`LoadError`] if the backend fails to initialise or the
64    /// model cannot be loaded.
65    pub fn from_gguf(
66        model_path: impl Into<String>,
67        n_gpu_layers: u32,
68        n_ctx: u32,
69    ) -> Result<Self, LoadError> {
70        let model_path = model_path.into();
71        let (request_tx, mut request_rx) = mpsc::unbounded_channel::<EmbeddingCommand>();
72        let (init_tx, init_rx) = std::sync::mpsc::channel::<Result<usize, LoadError>>();
73
74        let worker_handle = thread::spawn(move || {
75            embedding_worker(&model_path, n_gpu_layers, n_ctx, init_tx, &mut request_rx);
76        });
77
78        let ndims = init_rx
79            .recv()
80            .map_err(|_| LoadError::WorkerInitDisconnected)??;
81
82        Ok(Self {
83            request_tx,
84            ndims,
85            worker_handle: Some(worker_handle),
86        })
87    }
88
89    /// Create an embedding model handle from this client.
90    pub fn embedding_model(&self, model: impl Into<String>) -> EmbeddingModelHandle {
91        self.embedding_model_with_ndims(model, self.ndims)
92    }
93
94    /// Create an embedding model handle with explicit dimensions.
95    pub fn embedding_model_with_ndims(
96        &self,
97        model: impl Into<String>,
98        ndims: usize,
99    ) -> EmbeddingModelHandle {
100        let wire = Local::new(crate::PROVIDER)
101            .with_id(model)
102            .with_capabilities(Capabilities::embedding(MAX_DOCUMENTS, ndims));
103        rig_core::Model::new(
104            wire,
105            EmbeddingRuntime {
106                request_tx: self.request_tx.clone(),
107            },
108        )
109    }
110}
111
112impl Drop for EmbeddingClient {
113    fn drop(&mut self) {
114        let _ = self.request_tx.send(EmbeddingCommand::Shutdown);
115
116        if let Some(worker_handle) = self.worker_handle.take() {
117            let _ = worker_handle.join();
118        }
119    }
120}
121
122/// A loaded embedding model: Rig's local embedding wire over the embedding
123/// worker.
124///
125/// Obtained via [`EmbeddingClient::embedding_model`]. Call it directly
126/// (`model.embed_text(..)`, `model.call(texts)`), or erase it with
127/// `.erase()` / `.into()` wherever Rig takes a `DynModel<Embedding>`, such as
128/// `EmbeddingsBuilder`.
129pub type EmbeddingModelHandle = rig_core::Model<Local<EmbeddingOp>, EmbeddingRuntime>;
130
131/// The transport behind [`EmbeddingModelHandle`]: it hands each batch of
132/// texts to the embedding worker thread.
133#[derive(Clone)]
134pub struct EmbeddingRuntime {
135    request_tx: mpsc::UnboundedSender<EmbeddingCommand>,
136}
137
138impl Transport<Local<EmbeddingOp>> for EmbeddingRuntime {
139    fn send(&self, texts: Vec<String>, _exchange: Exchange) -> Opening<Step<EmbeddingOp>> {
140        let request_tx = self.request_tx.clone();
141        Opening::new(async move {
142            let (tx, rx) = oneshot::channel();
143            request_tx
144                .send(EmbeddingCommand::Request(EmbeddingRequest {
145                    texts,
146                    response_tx: tx,
147                }))
148                .map_err(|_| ProviderError::Provider("Embedding worker shut down".into()))?;
149
150            let vectors = rx
151                .await
152                .map_err(|_| ProviderError::Provider("Response channel closed".into()))?
153                .map_err(ProviderError::Provider)?;
154
155            // Rig's embedding fold pairs each vector with its input text.
156            let response = EmbeddingResponse::new(
157                vectors
158                    .into_iter()
159                    .map(|vec| Embedding {
160                        document: String::new(),
161                        vec: vec.into_iter().map(f64::from).collect(),
162                    })
163                    .collect(),
164            );
165            Ok(Opened::new(tokio_stream::iter([Ok(Step::End(response))])))
166        })
167    }
168}
169
170// === Embedding worker (runs on dedicated thread) ===
171
172fn embedding_worker(
173    model_path: &str,
174    n_gpu_layers: u32,
175    n_ctx: u32,
176    init_tx: std::sync::mpsc::Sender<Result<usize, LoadError>>,
177    rx: &mut mpsc::UnboundedReceiver<EmbeddingCommand>,
178) {
179    use llama_cpp_2::list_llama_ggml_backend_devices;
180    use llama_cpp_2::model::LlamaModel as LlamaCppModel;
181    use llama_cpp_2::model::params::LlamaModelParams;
182
183    let backend = match crate::shared_backend() {
184        Ok(b) => b,
185        Err(e) => {
186            let _ = init_tx.send(Err(LoadError::BackendInit(e)));
187            return;
188        }
189    };
190    let mut model_params = LlamaModelParams::default().with_n_gpu_layers(n_gpu_layers);
191
192    if backend.supports_gpu_offload() {
193        let vulkan_devices: Vec<usize> = list_llama_ggml_backend_devices()
194            .into_iter()
195            .filter(|device| device.backend.eq_ignore_ascii_case("vulkan"))
196            .map(|device| device.index)
197            .collect();
198
199        if !vulkan_devices.is_empty() {
200            model_params = match model_params.with_devices(&vulkan_devices) {
201                Ok(params) => {
202                    log::info!("Using Vulkan backend devices: {vulkan_devices:?}");
203                    params
204                }
205                Err(e) => {
206                    let _ = init_tx.send(Err(LoadError::ConfigureDevices(e.to_string())));
207                    return;
208                }
209            };
210        }
211    }
212
213    log::info!("Loading embedding model from {model_path}...");
214
215    let model = match LlamaCppModel::load_from_file(backend, model_path, &model_params) {
216        Ok(m) => m,
217        Err(e) => {
218            let _ = init_tx.send(Err(LoadError::ModelLoad(e.to_string())));
219            return;
220        }
221    };
222
223    let ndims = model.n_embd() as usize;
224    log::info!("Embedding model loaded (ndims={ndims}).");
225
226    let _ = init_tx.send(Ok(ndims));
227
228    while let Some(command) = rx.blocking_recv() {
229        let req = match command {
230            EmbeddingCommand::Request(req) => req,
231            EmbeddingCommand::Shutdown => break,
232        };
233
234        let result = run_embedding(backend, &model, n_ctx, &req.texts);
235        let _ = req.response_tx.send(result);
236    }
237}
238
239fn run_embedding(
240    backend: &llama_cpp_2::llama_backend::LlamaBackend,
241    model: &llama_cpp_2::model::LlamaModel,
242    n_ctx: u32,
243    texts: &[String],
244) -> Result<Vec<Vec<f32>>, String> {
245    use llama_cpp_2::context::params::LlamaContextParams;
246    use llama_cpp_2::llama_batch::LlamaBatch;
247    // Encoder-only embedding models require `n_ubatch >= n_tokens` for
248    // every single sequence in the batch (llama.cpp asserts on this).
249    // The default `n_ubatch` is 512, which is smaller than a typical
250    // chunk's token count, so we widen both the batch and micro-batch to
251    // match `n_ctx`. This lets any chunk that fits the context window also
252    // fit in one micro-batch step.
253    let ctx_params = LlamaContextParams::default()
254        .with_n_ctx(NonZeroU32::new(n_ctx).map(Some).unwrap_or(None))
255        .with_n_batch(n_ctx)
256        .with_n_ubatch(n_ctx)
257        .with_n_seq_max(1)
258        .with_embeddings(true);
259
260    let mut ctx = model
261        .new_context(backend, ctx_params)
262        .map_err(|e| format!("Embedding context creation failed: {e}"))?;
263
264    let batch_limit = ctx.n_batch().max(1) as usize;
265
266    // Encode each text in its own single-sequence batch. Packing multiple
267    // sequences into one batch trips a `ggml_can_mul_mat` assert on
268    // mixture-of-experts architectures (e.g. nomic-embed-text-v2-moe) where
269    // expert routing produces incompatible tensor shapes across concurrent
270    // sequences. One-at-a-time encoding is correct for every architecture at
271    // the cost of some throughput.
272    let mut results = Vec::with_capacity(texts.len());
273    for text in texts {
274        let tokens = model.vocab().tokenize(text.as_bytes(), true, true);
275
276        // Tokenise in chunks that fit `batch_limit` (very long inputs).
277        for chunk in tokens.chunks(batch_limit) {
278            let mut batch = LlamaBatch::new(batch_limit, 1);
279            for (pos, &token) in chunk.iter().enumerate() {
280                batch
281                    .add(token, pos as i32, &[0], true)
282                    .map_err(|e| format!("Batch add failed: {e}"))?;
283            }
284            ctx.encode(&mut batch)
285                .map_err(|e| format!("Embedding encode failed: {e}"))?;
286        }
287
288        let emb = ctx
289            .embeddings_seq_ith(0)
290            .map_err(|e| format!("Failed to get embedding: {e}"))?;
291        results.push(emb.to_vec());
292
293        ctx.clear_kv_cache();
294    }
295
296    Ok(results)
297}