gllm 0.10.6

Pure Rust library for local embeddings, reranking, and text generation with MoE-optimized inference and aggressive performance tuning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! Runtime fallback embedder that automatically switches from GPU to CPU on failure.
//!
//! This module provides `FallbackEmbedder` which wraps `EmbedderHandle` and adds:
//! - Automatic GPU→CPU fallback on OOM or other GPU errors
//! - Lazy CPU backend initialization (only when needed)
//! - Transparent API compatible with `EmbedderHandle`
//!
//! ## Usage
//!
//! ```rust,ignore
//! use gllm::{FallbackEmbedder, Device};
//!
//! // Create with auto device selection (prefer GPU, fallback to CPU)
//! let embedder = FallbackEmbedder::new("bge-small-en").await?;
//!
//! // Embed text - automatically falls back to CPU if GPU fails
//! let vector = embedder.embed("Hello world").await?;
//! ```

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;

use crate::handle::EmbedderHandle;
use crate::types::{Device, Error, GraphCodeInput, Result};

#[cfg(feature = "tokio")]
use tokio::sync::Mutex;

#[cfg(not(feature = "tokio"))]
use std::sync::Mutex;

/// Maximum consecutive GPU failures before switching to CPU-only mode.
const MAX_GPU_FAILURES: usize = 3;

/// Embedder with automatic runtime fallback from GPU to CPU.
///
/// This wrapper provides transparent fallback handling:
/// 1. Starts with GPU (if available via Device::Auto)
/// 2. On GPU failure (OOM, driver error, etc.), retries with CPU
/// 3. After MAX_GPU_FAILURES, permanently switches to CPU mode
///
/// The CPU embedder is lazily initialized only when fallback is needed,
/// avoiding unnecessary resource usage when GPU works fine.
pub struct FallbackEmbedder {
    /// Primary embedder (GPU or Auto)
    primary: Arc<Mutex<EmbedderHandle>>,
    /// CPU fallback embedder (lazy initialized)
    fallback: Arc<Mutex<Option<EmbedderHandle>>>,
    /// Model name for creating fallback
    model_name: String,
    /// Whether GPU mode is disabled (after repeated failures)
    gpu_disabled: Arc<AtomicBool>,
    /// Consecutive GPU failure counter
    failure_count: Arc<AtomicUsize>,
}

impl FallbackEmbedder {
    /// Create a new fallback embedder with auto device selection.
    ///
    /// Prefers GPU, automatically falls back to CPU on failure.
    #[cfg(feature = "tokio")]
    pub async fn new(model: &str) -> Result<Self> {
        Self::new_with_device(model, Device::Auto).await
    }

    /// Create a fallback embedder with specified primary device.
    ///
    /// If primary device fails, will fall back to CPU.
    #[cfg(feature = "tokio")]
    pub async fn new_with_device(model: &str, device: Device) -> Result<Self> {
        let primary = EmbedderHandle::new_with_device(model, device).await?;

        Ok(Self {
            primary: Arc::new(Mutex::new(primary)),
            fallback: Arc::new(Mutex::new(None)),
            model_name: model.to_string(),
            gpu_disabled: Arc::new(AtomicBool::new(false)),
            failure_count: Arc::new(AtomicUsize::new(0)),
        })
    }

    /// Create a new fallback embedder (sync version).
    #[cfg(not(feature = "tokio"))]
    pub fn new(model: &str) -> Result<Self> {
        Self::new_with_device(model, Device::Auto)
    }

    /// Create a fallback embedder with specified primary device (sync version).
    #[cfg(not(feature = "tokio"))]
    pub fn new_with_device(model: &str, device: Device) -> Result<Self> {
        let primary = EmbedderHandle::new_with_device(model, device)?;

        Ok(Self {
            primary: Arc::new(Mutex::new(primary)),
            fallback: Arc::new(Mutex::new(None)),
            model_name: model.to_string(),
            gpu_disabled: Arc::new(AtomicBool::new(false)),
            failure_count: Arc::new(AtomicUsize::new(0)),
        })
    }

    /// Check if GPU mode is currently disabled.
    pub fn is_gpu_disabled(&self) -> bool {
        self.gpu_disabled.load(Ordering::Relaxed)
    }

    /// Get the current failure count.
    pub fn failure_count(&self) -> usize {
        self.failure_count.load(Ordering::Relaxed)
    }

    /// Reset failure count and re-enable GPU mode.
    ///
    /// Call this after GPU becomes available again (e.g., after freeing VRAM).
    pub fn reset_gpu(&self) {
        self.failure_count.store(0, Ordering::Relaxed);
        self.gpu_disabled.store(false, Ordering::Relaxed);
    }

    /// Get or create the CPU fallback embedder.
    #[cfg(feature = "tokio")]
    async fn get_or_create_fallback(&self) -> Result<()> {
        let mut guard = self.fallback.lock().await;
        if guard.is_none() {
            eprintln!("🔄 gllm: Initializing CPU fallback embedder...");
            let cpu_embedder = EmbedderHandle::new_with_device(&self.model_name, Device::Cpu).await?;
            eprintln!("✅ gllm: CPU fallback ready");
            *guard = Some(cpu_embedder);
        }
        Ok(())
    }

    #[cfg(not(feature = "tokio"))]
    fn get_or_create_fallback(&self) -> Result<()> {
        let mut guard = self.fallback.lock().map_err(|e| {
            Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
        })?;
        if guard.is_none() {
            eprintln!("🔄 gllm: Initializing CPU fallback embedder...");
            let cpu_embedder = EmbedderHandle::new_with_device(&self.model_name, Device::Cpu)?;
            eprintln!("✅ gllm: CPU fallback ready");
            *guard = Some(cpu_embedder);
        }
        Ok(())
    }

    /// Embed a single text with automatic fallback.
    #[cfg(feature = "tokio")]
    pub async fn embed(&self, text: &str) -> Result<Vec<f32>> {
        // If GPU is disabled, use fallback directly
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback().await?;
            let guard = self.fallback.lock().await;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed(text).await;
        }

        // Try primary (GPU)
        let primary = self.primary.lock().await;
        match primary.embed(text).await {
            Ok(result) => {
                // Success - reset failure count
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary); // Release lock before fallback
                self.handle_gpu_failure(&e).await?;

                // Retry with fallback
                let guard = self.fallback.lock().await;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed(text).await
            }
            Err(e) => Err(e),
        }
    }

    /// Embed multiple texts in batch with automatic fallback.
    #[cfg(feature = "tokio")]
    pub async fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        // If GPU is disabled, use fallback directly
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback().await?;
            let guard = self.fallback.lock().await;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed_batch(texts).await;
        }

        // Try primary (GPU)
        let primary = self.primary.lock().await;
        match primary.embed_batch(texts).await {
            Ok(result) => {
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary);
                self.handle_gpu_failure(&e).await?;

                let guard = self.fallback.lock().await;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed_batch(texts).await
            }
            Err(e) => Err(e),
        }
    }

    /// Embed graph code inputs with automatic fallback.
    #[cfg(feature = "tokio")]
    pub async fn embed_graph_batch(&self, inputs: Vec<GraphCodeInput>) -> Result<Vec<Vec<f32>>> {
        // If GPU is disabled, use fallback directly
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback().await?;
            let guard = self.fallback.lock().await;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed_graph_batch(inputs).await;
        }

        // Try primary (GPU)
        let primary = self.primary.lock().await;
        match primary.embed_graph_batch(inputs.clone()).await {
            Ok(result) => {
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary);
                self.handle_gpu_failure(&e).await?;

                let guard = self.fallback.lock().await;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed_graph_batch(inputs).await
            }
            Err(e) => Err(e),
        }
    }

    /// Handle GPU failure: increment counter, possibly disable GPU, init fallback.
    #[cfg(feature = "tokio")]
    async fn handle_gpu_failure(&self, error: &Error) -> Result<()> {
        let failures = self.failure_count.fetch_add(1, Ordering::Relaxed) + 1;
        eprintln!(
            "⚠️ gllm: GPU failure {}/{}: {}",
            failures, MAX_GPU_FAILURES, error
        );

        if failures >= MAX_GPU_FAILURES {
            eprintln!("🚫 gllm: GPU disabled after {} failures, switching to CPU-only mode", failures);
            self.gpu_disabled.store(true, Ordering::Relaxed);
        }

        // Initialize fallback
        self.get_or_create_fallback().await
    }

    // ==================== Sync versions ====================

    #[cfg(not(feature = "tokio"))]
    pub fn embed(&self, text: &str) -> Result<Vec<f32>> {
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback()?;
            let guard = self.fallback.lock().map_err(|e| {
                Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
            })?;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed(text);
        }

        let primary = self.primary.lock().map_err(|e| {
            Error::InternalError(format!("Failed to lock primary mutex: {}", e))
        })?;

        match primary.embed(text) {
            Ok(result) => {
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary);
                self.handle_gpu_failure_sync(&e)?;

                let guard = self.fallback.lock().map_err(|e| {
                    Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
                })?;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed(text)
            }
            Err(e) => Err(e),
        }
    }

    #[cfg(not(feature = "tokio"))]
    pub fn embed_batch(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback()?;
            let guard = self.fallback.lock().map_err(|e| {
                Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
            })?;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed_batch(texts);
        }

        let primary = self.primary.lock().map_err(|e| {
            Error::InternalError(format!("Failed to lock primary mutex: {}", e))
        })?;

        match primary.embed_batch(texts) {
            Ok(result) => {
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary);
                self.handle_gpu_failure_sync(&e)?;

                let guard = self.fallback.lock().map_err(|e| {
                    Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
                })?;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed_batch(texts)
            }
            Err(e) => Err(e),
        }
    }

    #[cfg(not(feature = "tokio"))]
    pub fn embed_graph_batch(&self, inputs: Vec<GraphCodeInput>) -> Result<Vec<Vec<f32>>> {
        if self.gpu_disabled.load(Ordering::Relaxed) {
            self.get_or_create_fallback()?;
            let guard = self.fallback.lock().map_err(|e| {
                Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
            })?;
            return guard.as_ref()
                .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                .embed_graph_batch(inputs);
        }

        let primary = self.primary.lock().map_err(|e| {
            Error::InternalError(format!("Failed to lock primary mutex: {}", e))
        })?;

        match primary.embed_graph_batch(inputs.clone()) {
            Ok(result) => {
                self.failure_count.store(0, Ordering::Relaxed);
                Ok(result)
            }
            Err(e) if e.is_oom() => {
                drop(primary);
                self.handle_gpu_failure_sync(&e)?;

                let guard = self.fallback.lock().map_err(|e| {
                    Error::InternalError(format!("Failed to lock fallback mutex: {}", e))
                })?;
                guard.as_ref()
                    .ok_or_else(|| Error::InternalError("Fallback not initialized".into()))?
                    .embed_graph_batch(inputs)
            }
            Err(e) => Err(e),
        }
    }

    #[cfg(not(feature = "tokio"))]
    fn handle_gpu_failure_sync(&self, error: &Error) -> Result<()> {
        let failures = self.failure_count.fetch_add(1, Ordering::Relaxed) + 1;
        eprintln!(
            "⚠️ gllm: GPU failure {}/{}: {}",
            failures, MAX_GPU_FAILURES, error
        );

        if failures >= MAX_GPU_FAILURES {
            eprintln!("🚫 gllm: GPU disabled after {} failures, switching to CPU-only mode", failures);
            self.gpu_disabled.store(true, Ordering::Relaxed);
        }

        self.get_or_create_fallback()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "tokio")]
    #[tokio::test]
    async fn test_fallback_embedder_creation() {
        // Just test creation - actual embedding tested in handle.rs
        let embedder = FallbackEmbedder::new("bge-small-en").await;
        assert!(embedder.is_ok());

        let embedder = embedder.unwrap();
        assert!(!embedder.is_gpu_disabled());
        assert_eq!(embedder.failure_count(), 0);
    }

    #[cfg(feature = "tokio")]
    #[tokio::test]
    async fn test_reset_gpu() {
        let embedder = FallbackEmbedder::new("bge-small-en").await.unwrap();

        // Simulate failures
        embedder.failure_count.store(5, Ordering::Relaxed);
        embedder.gpu_disabled.store(true, Ordering::Relaxed);

        assert!(embedder.is_gpu_disabled());
        assert_eq!(embedder.failure_count(), 5);

        // Reset
        embedder.reset_gpu();

        assert!(!embedder.is_gpu_disabled());
        assert_eq!(embedder.failure_count(), 0);
    }
}