embellama 0.10.1

High-performance Rust library for generating text embeddings using llama-cpp
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
425
426
427
428
429
430
431
// Copyright 2025 Embellama Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod common;

use common::*;
use embellama::{CacheConfigBuilder, EmbeddingEngine, EngineConfigBuilder, NormalizationMode};
use std::time::Instant;

#[test]
#[ignore = "Requires model file"]
fn test_engine_with_cache_enabled() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    // Create engine with cache enabled
    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_config(
            CacheConfigBuilder::new()
                .with_enabled(true)
                .with_embedding_cache_size(100)
                .with_ttl_seconds(3600)
                .build()
                .expect("Failed to build cache config"),
        )
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Verify cache is enabled
    assert!(engine.is_cache_enabled());

    // Generate embedding twice for the same text
    let text = "This is a test for caching functionality";

    // First call - should miss cache
    let start = Instant::now();
    let embedding1 = engine
        .embed(None, text)
        .expect("Failed to generate embedding");
    let time_uncached = start.elapsed();

    // Second call - should hit cache
    let start = Instant::now();
    let embedding2 = engine
        .embed(None, text)
        .expect("Failed to generate embedding");
    let time_cached = start.elapsed();

    // Embeddings should be identical
    assert_eq!(embedding1, embedding2);

    // Cached call should be significantly faster
    // > NOTE: Cache lookup should be < 1ms, model inference is typically > 10ms
    assert!(
        time_cached < time_uncached / 5,
        "Cached call should be at least 5x faster. Uncached: {:?}, Cached: {:?}",
        time_uncached,
        time_cached
    );

    // Check cache statistics
    let stats = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats.hits, 1);
    assert_eq!(stats.misses, 1);
    assert_eq!(stats.entry_count, 1);
    assert!(stats.hit_rate > 0.0 && stats.hit_rate <= 1.0);
}

#[test]
#[ignore = "Requires model file"]
fn test_engine_with_cache_disabled() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    // Create engine with cache disabled
    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_disabled()
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Verify cache is disabled
    assert!(!engine.is_cache_enabled());

    // Generate embedding twice
    let text = "Test without caching";
    let embedding1 = engine
        .embed(None, text)
        .expect("Failed to generate embedding");
    let embedding2 = engine
        .embed(None, text)
        .expect("Failed to generate embedding");

    // Embeddings should still be identical (same input)
    assert_eq!(embedding1, embedding2);

    // No cache statistics should be available
    assert!(engine.get_cache_stats().is_none());
}

#[test]
#[ignore = "Requires model file"]
fn test_cache_batch_processing() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    // Create engine with cache
    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_enabled()
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Prepare batch with duplicates
    let texts = vec![
        "First unique text",
        "Second unique text",
        "First unique text", // Duplicate
        "Third unique text",
        "Second unique text", // Duplicate
    ];

    // First batch - all cache misses
    let embeddings1 = engine
        .embed_batch(None, &texts)
        .expect("Failed to generate batch embeddings");

    assert_eq!(embeddings1.len(), 5);

    // Check that duplicates have identical embeddings
    assert_eq!(embeddings1[0], embeddings1[2]); // First text duplicates
    assert_eq!(embeddings1[1], embeddings1[4]); // Second text duplicates

    // Second batch with same texts - should hit cache
    let start = Instant::now();
    let embeddings2 = engine
        .embed_batch(None, &texts)
        .expect("Failed to generate batch embeddings");
    let cached_time = start.elapsed();

    // All embeddings should be identical to first batch
    for (e1, e2) in embeddings1.iter().zip(embeddings2.iter()) {
        assert_eq!(e1, e2);
    }

    // Check cache statistics
    let stats = engine.get_cache_stats().expect("Cache should be enabled");
    // We have 3 unique texts, but called them multiple times
    assert_eq!(stats.entry_count, 3);
    // Second batch should have 5 hits (all texts were cached)
    assert!(stats.hits >= 5);

    println!("Batch cache lookup time: {:?}", cached_time);
}

#[test]
#[ignore = "Requires model file"]
fn test_cache_clearing() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_enabled()
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Generate some embeddings to populate cache
    let texts = vec!["text1", "text2", "text3"];
    for text in &texts {
        engine
            .embed(None, text)
            .expect("Failed to generate embedding");
    }

    // Verify cache has entries
    let stats_before = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats_before.entry_count, 3);

    // Clear cache
    engine.clear_cache();

    // Verify cache is empty
    let stats_after = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats_after.entry_count, 0);
    assert_eq!(stats_after.hits, 0);
    assert_eq!(stats_after.misses, 0);

    // Generate embedding again - should be a cache miss
    engine
        .embed(None, texts[0])
        .expect("Failed to generate embedding");
    let stats_final = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats_final.misses, 1);
    assert_eq!(stats_final.hits, 0);
}

#[test]
#[ignore = "Requires model file"]
fn test_cache_warm_up() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_enabled()
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Warm up cache with common texts
    let warm_up_texts = vec![
        "Frequently used text 1",
        "Frequently used text 2",
        "Frequently used text 3",
    ];

    engine
        .warm_cache(None, &warm_up_texts)
        .expect("Failed to warm cache");

    // Verify all texts are in cache
    let stats = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats.entry_count, 3);

    // Now using these texts should hit cache
    for text in &warm_up_texts {
        let start = Instant::now();
        engine
            .embed(None, text)
            .expect("Failed to generate embedding");
        let elapsed = start.elapsed();
        // Should be very fast (< 1ms typically)
        assert!(
            elapsed.as_millis() < 10,
            "Cache hit took too long: {:?}",
            elapsed
        );
    }

    // All should be hits
    let final_stats = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(final_stats.hits, 3);
}

#[test]
#[ignore = "Requires model file"]
fn test_cache_with_different_models() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    // Create engine with cache
    let config = EngineConfigBuilder::new()
        .with_model_path(model_path.clone())
        .with_model_name("model1")
        .with_cache_enabled()
        .build()
        .expect("Failed to build config");

    let mut engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Load a second model configuration (using same file for testing)
    let config2 = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("model2")
        .with_normalization_mode(NormalizationMode::None) // Different normalization
        .build()
        .expect("Failed to build config");

    engine
        .load_model(config2)
        .expect("Failed to load second model");

    let text = "Same text for different models";

    // Generate with first model
    let embedding1 = engine
        .embed(Some("model1"), text)
        .expect("Failed to generate embedding");

    // Generate with second model - should be cache miss (different model)
    let embedding2 = engine
        .embed(Some("model2"), text)
        .expect("Failed to generate embedding");

    // Different normalization (L2 vs None) should produce different embeddings
    assert_ne!(
        embedding1, embedding2,
        "Different normalization modes should produce different embeddings"
    );
    // But both should be in cache now
    let stats = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(stats.entry_count, 2); // Two different cache keys

    // Requesting again should hit cache for both
    let _ = engine
        .embed(Some("model1"), text)
        .expect("Failed to generate embedding");
    let _ = engine
        .embed(Some("model2"), text)
        .expect("Failed to generate embedding");

    let final_stats = engine.get_cache_stats().expect("Cache should be enabled");
    assert_eq!(final_stats.hits, 2);
}

#[test]
fn test_cache_key_differences() {
    use embellama::PoolingStrategy;
    use embellama::cache::embedding_cache::EmbeddingCache;

    let text = "Test text";
    let model = "test-model";

    // Different configurations should produce different cache keys
    let key1 =
        EmbeddingCache::compute_key(text, model, PoolingStrategy::Mean, NormalizationMode::L2);
    let key2 =
        EmbeddingCache::compute_key(text, model, PoolingStrategy::Mean, NormalizationMode::None);
    let key3 =
        EmbeddingCache::compute_key(text, model, PoolingStrategy::Cls, NormalizationMode::L2);
    let key4 =
        EmbeddingCache::compute_key(text, model, PoolingStrategy::Max, NormalizationMode::L2);
    let key5 = EmbeddingCache::compute_key(
        text,
        "different-model",
        PoolingStrategy::Mean,
        NormalizationMode::L2,
    );

    // All keys should be different
    assert_ne!(key1, key2); // Different normalization
    assert_ne!(key1, key3); // Different pooling
    assert_ne!(key1, key4); // Different pooling
    assert_ne!(key1, key5); // Different model

    // Same configuration should produce same key
    let key1_duplicate =
        EmbeddingCache::compute_key(text, model, PoolingStrategy::Mean, NormalizationMode::L2);
    assert_eq!(key1, key1_duplicate);
}

#[test]
#[ignore = "Requires model file"]
fn test_mixed_batch_cache_hits() {
    let Some(model_path) = get_test_model_path() else {
        eprintln!("Skipping test: no test model configured");
        return;
    };

    let config = EngineConfigBuilder::new()
        .with_model_path(model_path)
        .with_model_name("test-model")
        .with_cache_enabled()
        .build()
        .expect("Failed to build config");

    let engine = EmbeddingEngine::new(config).expect("Failed to create engine");

    // Pre-populate cache with some texts
    let cached_texts = vec!["cached1", "cached2"];
    for text in &cached_texts {
        engine
            .embed(None, text)
            .expect("Failed to generate embedding");
    }

    // Create batch with mix of cached and new texts
    let mixed_batch = vec![
        "cached1", // Hit
        "new1",    // Miss
        "cached2", // Hit
        "new2",    // Miss
        "cached1", // Hit (duplicate)
    ];

    let embeddings = engine
        .embed_batch(None, &mixed_batch)
        .expect("Failed to generate batch");

    assert_eq!(embeddings.len(), 5);

    // Check cache statistics
    let stats = engine.get_cache_stats().expect("Cache should be enabled");

    // We should have 4 unique texts in cache now
    assert_eq!(stats.entry_count, 4);

    // The batch should have had 3 hits (cached1 twice, cached2 once)
    // and 2 misses (new1, new2)
    // Plus the original 2 misses from pre-population
    println!("Cache stats: {:?}", stats);
}