rig_llama_cpp/
embedding.rs1use 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
13const 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
26pub struct EmbeddingClient {
47 request_tx: mpsc::UnboundedSender<EmbeddingCommand>,
48 ndims: usize,
49 worker_handle: Option<thread::JoinHandle<()>>,
50}
51
52impl EmbeddingClient {
53 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 pub fn embedding_model(&self, model: impl Into<String>) -> EmbeddingModelHandle {
91 self.embedding_model_with_ndims(model, self.ndims)
92 }
93
94 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
122pub type EmbeddingModelHandle = rig_core::Model<Local<EmbeddingOp>, EmbeddingRuntime>;
130
131#[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 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
170fn 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 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 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 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}