realizar 0.8.5

Pure Rust ML inference engine built from scratch - model serving for GGUF and safetensors
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449

// ============================================================================
// Tests: Sampling Algorithms Coverage (PMAT-802)
// ============================================================================

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

    // Helper to create logits tensor (panics on empty - use make_empty_logits for that)
    fn make_logits(data: &[f32]) -> Tensor<f32> {
        assert!(!data.is_empty(), "Use make_empty_logits for empty data");
        Tensor::from_vec(vec![data.len()], data.to_vec()).expect("expected value")
    }

    // Create a single-element tensor to simulate edge case (empty logits not valid)
    fn make_single_logit() -> Tensor<f32> {
        Tensor::from_vec(vec![1], vec![0.0]).expect("expected value")
    }

    // ========================================================================
    // Min-P Sampling Tests
    // ========================================================================

    #[test]
    fn test_sample_min_p_basic() {
        let logits = make_logits(&[2.0, 1.0, 0.5, 0.1]);
        let result = sample_min_p(&logits, 0.1, 0.5);
        assert!(result.is_ok());
        let idx = result.expect("idx");
        assert!(idx < 4);
    }

    #[test]
    fn test_sample_min_p_single_logit() {
        // Single logit should work (edge case - only one choice)
        let logits = make_single_logit();
        let result = sample_min_p(&logits, 0.1, 0.5);
        assert!(result.is_ok());
        assert_eq!(result.expect("result"), 0);
    }

    #[test]
    fn test_sample_min_p_invalid_min_p_negative() {
        let logits = make_logits(&[1.0, 2.0, 3.0]);
        let result = sample_min_p(&logits, -0.1, 0.5);
        assert!(result.is_err());
    }

    #[test]
    fn test_sample_min_p_invalid_min_p_too_high() {
        let logits = make_logits(&[1.0, 2.0, 3.0]);
        let result = sample_min_p(&logits, 1.5, 0.5);
        assert!(result.is_err());
    }

    #[test]
    fn test_sample_min_p_high_threshold_fallback() {
        // With very high min_p, all tokens filtered -> fallback to greedy
        let logits = make_logits(&[1.0, 5.0, 2.0]);
        let result = sample_min_p(&logits, 0.99, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_min_p_zero_threshold() {
        // With min_p=0, all tokens kept
        let logits = make_logits(&[1.0, 2.0, 3.0]);
        let result = sample_min_p(&logits, 0.0, 0.5);
        assert!(result.is_ok());
    }

    // ========================================================================
    // Mirostat State Tests
    // ========================================================================

    #[test]
    fn test_mirostat_state_default() {
        let state = MirostatState::default();
        assert!((state.tau - 5.0).abs() < 1e-6);
        assert!((state.eta - 0.1).abs() < 1e-6);
        assert!((state.mu - 10.0).abs() < 1e-6);
    }

    #[test]
    fn test_mirostat_state_new() {
        let state = MirostatState::new(3.0);
        assert!((state.tau - 3.0).abs() < 1e-6);
        assert!((state.mu - 6.0).abs() < 1e-6); // 2 * tau
    }

    #[test]
    fn test_mirostat_state_with_eta() {
        let state = MirostatState::new(5.0).with_eta(0.2);
        assert!((state.eta - 0.2).abs() < 1e-6);
    }

    #[test]
    fn test_mirostat_state_update() {
        let mut state = MirostatState::new(5.0).with_eta(0.1);
        let initial_mu = state.mu;
        state.update(6.0); // Observed surprise > tau
        assert!(state.mu < initial_mu); // mu decreases
    }

    #[test]
    fn test_mirostat_state_update_low_surprise() {
        let mut state = MirostatState::new(5.0).with_eta(0.1);
        let initial_mu = state.mu;
        state.update(4.0); // Observed surprise < tau
        assert!(state.mu > initial_mu); // mu increases
    }

    // ========================================================================
    // Mirostat Sampling Tests
    // ========================================================================

    #[test]
    fn test_sample_mirostat_basic() {
        let logits = make_logits(&[2.0, 1.0, 0.5, 0.1]);
        let mut state = MirostatState::default();
        let result = sample_mirostat(&logits, &mut state, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_mirostat_single_logit() {
        let logits = make_single_logit();
        let mut state = MirostatState::default();
        let result = sample_mirostat(&logits, &mut state, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_mirostat_state_updates() {
        let logits = make_logits(&[5.0, 1.0, 0.1]);
        let mut state = MirostatState::new(3.0);
        let initial_mu = state.mu;
        let _ = sample_mirostat(&logits, &mut state, 0.5);
        // State should be updated after sampling
        assert!((state.mu - initial_mu).abs() > 1e-9 || state.mu == initial_mu);
    }

    // ========================================================================
    // Tail-Free Sampling Tests
    // ========================================================================

    #[test]
    fn test_sample_tfs_basic() {
        let logits = make_logits(&[3.0, 2.0, 1.0, 0.5, 0.1]);
        let result = sample_tfs(&logits, 0.95, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_tfs_single_logit() {
        let logits = make_single_logit();
        let result = sample_tfs(&logits, 0.95, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_tfs_low_z() {
        let logits = make_logits(&[3.0, 2.0, 1.0]);
        let result = sample_tfs(&logits, 0.1, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_tfs_high_z() {
        let logits = make_logits(&[3.0, 2.0, 1.0]);
        let result = sample_tfs(&logits, 0.99, 0.5);
        assert!(result.is_ok());
    }

    // ========================================================================
    // Typical Sampling Tests
    // ========================================================================

    #[test]
    fn test_sample_typical_basic() {
        let logits = make_logits(&[3.0, 2.0, 1.0, 0.5]);
        let result = sample_typical(&logits, 0.95, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_typical_single_logit() {
        let logits = make_single_logit();
        let result = sample_typical(&logits, 0.95, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_typical_low_p() {
        let logits = make_logits(&[3.0, 2.0, 1.0]);
        let result = sample_typical(&logits, 0.1, 0.5);
        assert!(result.is_ok());
    }

    // ========================================================================
    // DRY Penalty Tests
    // ========================================================================

    #[test]
    fn test_dry_penalty_no_repetition() {
        let logits = make_logits(&[1.0, 2.0, 3.0, 4.0, 5.0]);
        let context = vec![0, 1, 2, 3]; // No repetition
        let config = DryConfig::default();
        let result = apply_dry_penalty(&logits, &context, &config);
        // Returns Tensor, verify it has same shape
        assert_eq!(result.shape(), logits.shape());
    }

    #[test]
    fn test_dry_penalty_with_repetition() {
        let logits = make_logits(&[1.0, 2.0, 3.0, 4.0, 5.0]);
        let context = vec![0, 1, 0, 1, 0]; // Repeating pattern
        let config = DryConfig {
            multiplier: 1.0,
            base: 1.5,
            allowed_length: 2,
            penalty_last_n: 256,
        };
        let result = apply_dry_penalty(&logits, &context, &config);
        assert_eq!(result.shape(), logits.shape());
    }

    #[test]
    fn test_dry_penalty_empty_context() {
        let logits = make_logits(&[1.0, 2.0, 3.0]);
        let context: Vec<usize> = vec![];
        let config = DryConfig::default();
        let result = apply_dry_penalty(&logits, &context, &config);
        assert_eq!(result.shape(), logits.shape());
    }

    #[test]
    fn test_dry_config_default() {
        let config = DryConfig::default();
        assert!(config.multiplier > 0.0);
        assert!(config.is_enabled());
    }

    #[test]
    fn test_dry_config_new() {
        let config = DryConfig::new(0.5);
        assert!((config.multiplier - 0.5).abs() < 1e-6);
    }

    #[test]
    fn test_dry_config_builder() {
        let config = DryConfig::new(1.0)
            .with_base(2.0)
            .with_allowed_length(3)
            .with_penalty_last_n(128);
        assert!((config.base - 2.0).abs() < 1e-6);
        assert_eq!(config.allowed_length, 3);
        assert_eq!(config.penalty_last_n, 128);
    }

    // ========================================================================
    // XTC Tests
    // ========================================================================

    #[test]
    fn test_apply_xtc_disabled() {
        let logits = make_logits(&[5.0, 4.0, 3.0, 2.0, 1.0]);
        let config = XtcConfig::default(); // probability=0.0 (disabled)
        let result = apply_xtc(&logits, &config, 0.5);
        // When disabled, should return original logits
        assert_eq!(result.shape(), logits.shape());
    }

    #[test]
    fn test_apply_xtc_enabled() {
        let logits = make_logits(&[5.0, 4.0, 3.0, 2.0, 1.0]);
        let config = XtcConfig::new(1.0).with_threshold(0.1);
        let result = apply_xtc(&logits, &config, 0.0); // rng < probability triggers
        assert_eq!(result.shape(), logits.shape());
    }

    #[test]
    fn test_xtc_config_default() {
        let config = XtcConfig::default();
        assert!((config.probability - 0.0).abs() < 1e-6);
        assert!(!config.is_enabled());
    }

    #[test]
    fn test_xtc_config_builder() {
        let config = XtcConfig::new(0.5).with_threshold(0.3).with_min_keep(2);
        assert!((config.probability - 0.5).abs() < 1e-6);
        assert!((config.threshold - 0.3).abs() < 1e-6);
        assert_eq!(config.min_keep, 2);
        assert!(config.is_enabled());
    }

    // ========================================================================
    // Eta Sampling Tests
    // ========================================================================

    #[test]
    fn test_sample_eta_basic() {
        let logits = make_logits(&[3.0, 2.0, 1.0, 0.5]);
        let config = EtaConfig::default();
        let result = sample_eta(&logits, &config, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_eta_single_logit() {
        let logits = make_single_logit();
        let config = EtaConfig::default();
        let result = sample_eta(&logits, &config, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_sample_eta_custom_config() {
        let logits = make_logits(&[3.0, 2.0, 1.0]);
        let config = EtaConfig::new(0.5);
        let result = sample_eta(&logits, &config, 0.5);
        assert!(result.is_ok());
    }

    #[test]
    fn test_eta_config_default() {
        let config = EtaConfig::default();
        assert!((config.eta - 0.3).abs() < 1e-6);
        assert!(config.min_p > 0.0);
    }

    // ========================================================================
    // Token Healing Tests
    // ========================================================================

    #[test]
    fn test_token_healing_empty_tokens() {
        let tokens: Vec<usize> = vec![];
        let result = analyze_token_healing(&tokens, None);
        assert_eq!(result.tokens_removed, 0);
        assert!(result.adjusted_tokens.is_empty());
    }

    #[test]
    fn test_token_healing_no_healing_needed() {
        let tokens = vec![1, 2, 3, 4, 5];
        let result = analyze_token_healing(&tokens, Some("hello")); // Long token, no healing
        assert_eq!(result.tokens_removed, 0);
        assert_eq!(result.adjusted_tokens.len(), 5);
    }

    #[test]
    fn test_token_healing_partial_token() {
        let tokens = vec![1, 2, 3, 4, 5];
        let result = analyze_token_healing(&tokens, Some("ab")); // Short alphanumeric
        // Should heal (remove last token, add prefix constraint)
        assert_eq!(result.tokens_removed, 1);
        assert_eq!(result.adjusted_tokens.len(), 4);
        assert!(result.prefix_constraint.is_some());
    }

    #[test]
    fn test_token_healing_with_space() {
        let tokens = vec![1, 2, 3];
        let result = analyze_token_healing(&tokens, Some(" the")); // Starts with space
        // Should NOT heal (tokens starting with space are complete)
        assert_eq!(result.tokens_removed, 0);
    }

    #[test]
    fn test_token_healing_config() {
        let config = TokenHealingConfig::new(true);
        assert!(config.enabled);
        assert!(config.max_backup_chars > 0);

        let config2 = TokenHealingConfig::new(true).with_max_backup(5);
        assert_eq!(config2.max_backup_chars, 5);
    }

    // ========================================================================
    // CFG (Classifier-Free Guidance) Tests
    // ========================================================================

    #[test]
    fn test_apply_cfg_basic() {
        let cond = make_logits(&[1.0, 2.0, 3.0]);
        let uncond = make_logits(&[0.5, 1.0, 1.5]);
        let result = apply_cfg(&cond, &uncond, 2.0);
        assert!(result.is_ok());
        let guided = result.expect("guided");
        assert_eq!(guided.shape(), cond.shape());
    }

    #[test]
    fn test_apply_cfg_shape_mismatch() {
        let cond = make_logits(&[1.0, 2.0, 3.0]);
        let uncond = make_logits(&[0.5, 1.0]);
        let result = apply_cfg(&cond, &uncond, 2.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_cfg_scale_one() {
        // With scale=1, output should equal conditional
        let cond = make_logits(&[1.0, 2.0, 3.0]);
        let uncond = make_logits(&[0.0, 0.0, 0.0]);
        let result = apply_cfg(&cond, &uncond, 1.0).expect("result");
        let data = result.data();
        assert!((data[0] - 1.0).abs() < 1e-6);
        assert!((data[1] - 2.0).abs() < 1e-6);
        assert!((data[2] - 3.0).abs() < 1e-6);
    }

    #[test]
    fn test_apply_cfg_scale_zero() {
        // With scale=0, output should equal unconditional
        let cond = make_logits(&[1.0, 2.0, 3.0]);
        let uncond = make_logits(&[0.5, 1.0, 1.5]);
        let result = apply_cfg(&cond, &uncond, 0.0).expect("result");
        let data = result.data();
        assert!((data[0] - 0.5).abs() < 1e-6);
        assert!((data[1] - 1.0).abs() < 1e-6);
        assert!((data[2] - 1.5).abs() < 1e-6);
    }

    #[test]
    fn test_apply_cfg_negative_scale() {
        // Negative scale should work (inverts guidance direction)
        let cond = make_logits(&[1.0, 2.0, 3.0]);
        let uncond = make_logits(&[0.5, 1.0, 1.5]);
        let result = apply_cfg(&cond, &uncond, -1.0);
        assert!(result.is_ok());
    }

    #[test]
    fn test_cfg_config_default() {
        let config = CfgConfig::default();
        assert!((config.scale - 1.0).abs() < 1e-6);
        assert!(config.negative_prompt_tokens.is_empty());
    }

    #[test]
    fn test_cfg_config_new() {
        let config = CfgConfig::new(2.0);
        assert!((config.scale - 2.0).abs() < 1e-6);
    }
}