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
//! T-COV-95 Coverage tests for quantize/mod.rs
//!
//! Covers:
//! - quantize_activations_q8k_into: success, error paths (not multiple of 256, buffer too small)
//! - quantize_to_q8_blocks: success, error path (not multiple of 32)
//! - dequantize_q8_blocks: round-trip
//! - InterleavedQ4K::from_q4k: success, error path
//! - InterleavedQ4K::num_values
//! - InterleavedQ4K::dot (scalar)
//! - fused_q4_0_q8_0_dot_scalar: known values
//! - fused_q4_0_q8_0_parallel_matvec: success and error paths
//! - fused_q4_0_q8_0_parallel_matvec_into: success and error paths
//! - f16_to_f32_lut: known values
//! - SimdBackend Display + Default
//! - DequantStats Default
//! - detect_simd_backend
//! - Q8_0Block::quantize, dequantize, quantization_error, relative_error
//! - Q8KSuperBlock::quantize, quantize_into, dequantize

use super::*;

// ============================================================================
// quantize_activations_q8k_into
// ============================================================================

#[test]
fn test_quantize_activations_q8k_into_success() {
    let activations = vec![1.0f32; 256];
    let mut scales = vec![0.0f32; 1];
    let mut quants = vec![0i8; 256];

    let result = quantize_activations_q8k_into(&activations, &mut scales, &mut quants);
    assert!(result.is_ok());
    assert!(scales[0] > 0.0, "Scale should be positive");
    // All same value -> all quants should be the same
    assert!(quants.iter().all(|&q| q == quants[0]));
}

#[test]
fn test_quantize_activations_q8k_into_two_superblocks() {
    let activations = vec![0.5f32; 512];
    let mut scales = vec![0.0f32; 2];
    let mut quants = vec![0i8; 512];

    let result = quantize_activations_q8k_into(&activations, &mut scales, &mut quants);
    assert!(result.is_ok());
    assert!(scales[0] > 0.0);
    assert!(scales[1] > 0.0);
}

#[test]
fn test_quantize_activations_q8k_into_not_multiple_of_256() {
    let activations = vec![1.0f32; 100]; // Not multiple of 256
    let mut scales = vec![0.0f32; 1];
    let mut quants = vec![0i8; 100];

    let result = quantize_activations_q8k_into(&activations, &mut scales, &mut quants);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("256"), "Error should mention 256: {}", err);
}

#[test]
fn test_quantize_activations_q8k_into_scales_too_small() {
    let activations = vec![1.0f32; 512]; // 2 superblocks
    let mut scales = vec![0.0f32; 1]; // Only room for 1
    let mut quants = vec![0i8; 512];

    let result = quantize_activations_q8k_into(&activations, &mut scales, &mut quants);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Scales") || err.contains("scales") || err.contains("too small"),
        "Error should mention scales buffer: {}",
        err
    );
}

#[test]
fn test_quantize_activations_q8k_into_quants_too_small() {
    let activations = vec![1.0f32; 256];
    let mut scales = vec![0.0f32; 1];
    let mut quants = vec![0i8; 100]; // Too small

    let result = quantize_activations_q8k_into(&activations, &mut scales, &mut quants);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Quants") || err.contains("quants") || err.contains("too small"),
        "Error should mention quants buffer: {}",
        err
    );
}

// ============================================================================
// quantize_to_q8_blocks / dequantize_q8_blocks
// ============================================================================

#[test]
fn test_quantize_to_q8_blocks_success() {
    let values = vec![1.0f32; 64]; // 2 blocks of 32
    let blocks = quantize_to_q8_blocks(&values).expect("should quantize");
    assert_eq!(blocks.len(), 2);
}

#[test]
fn test_quantize_to_q8_blocks_not_multiple_of_32() {
    let values = vec![1.0f32; 50]; // Not multiple of 32
    let result = quantize_to_q8_blocks(&values);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("32"), "Error should mention 32: {}", err);
}

#[test]
fn test_quantize_dequantize_round_trip() {
    let original = vec![0.5f32; 32];
    let blocks = quantize_to_q8_blocks(&original).expect("should quantize");
    let dequantized = dequantize_q8_blocks(&blocks);
    assert_eq!(dequantized.len(), 32);

    // Check approximate round-trip (quantization introduces error)
    for (o, d) in original.iter().zip(dequantized.iter()) {
        assert!(
            (o - d).abs() < 0.01,
            "Round-trip error too large: {} vs {}",
            o,
            d
        );
    }
}

#[test]
fn test_quantize_dequantize_varied_values() {
    let original: Vec<f32> = (0..32).map(|i| (i as f32 - 16.0) * 0.1).collect();
    let blocks = quantize_to_q8_blocks(&original).expect("should quantize");
    let dequantized = dequantize_q8_blocks(&blocks);

    for (o, d) in original.iter().zip(dequantized.iter()) {
        assert!(
            (o - d).abs() < 0.02,
            "Round-trip error too large: {} vs {}",
            o,
            d
        );
    }
}

#[test]
fn test_dequantize_q8_blocks_empty() {
    let blocks: Vec<Q8_0Block> = vec![];
    let output = dequantize_q8_blocks(&blocks);
    assert!(output.is_empty());
}

// ============================================================================
// InterleavedQ4K
// ============================================================================

#[test]
fn test_interleaved_q4k_from_q4k_success() {
    // 144 bytes per super-block
    let data = vec![0u8; 144];
    let result = InterleavedQ4K::from_q4k(&data);
    assert!(result.is_ok());
    let iq = result.unwrap();
    assert_eq!(iq.num_super_blocks, 1);
    assert_eq!(iq.num_values(), 256);
}

#[test]
fn test_interleaved_q4k_from_q4k_two_superblocks() {
    let data = vec![0u8; 288]; // 2 super-blocks
    let result = InterleavedQ4K::from_q4k(&data);
    assert!(result.is_ok());
    let iq = result.unwrap();
    assert_eq!(iq.num_super_blocks, 2);
    assert_eq!(iq.num_values(), 512);
    assert_eq!(iq.d.len(), 2);
    assert_eq!(iq.dmin.len(), 2);
    assert_eq!(iq.scales.len(), 24);
    assert_eq!(iq.qs.len(), 256);
}

#[test]
fn test_interleaved_q4k_from_q4k_invalid_length() {
    let data = vec![0u8; 100]; // Not multiple of 144
    let result = InterleavedQ4K::from_q4k(&data);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("144"), "Error should mention 144: {}", err);
}

#[test]
fn test_interleaved_q4k_from_q4k_empty() {
    let data: Vec<u8> = vec![];
    let result = InterleavedQ4K::from_q4k(&data);
    assert!(result.is_ok());
    let iq = result.unwrap();
    assert_eq!(iq.num_super_blocks, 0);
    assert_eq!(iq.num_values(), 0);
}

#[test]
fn test_interleaved_q4k_dot_scalar() {
    // Create a super-block with known values
    let mut data = vec![0u8; 144];
    // d = 1.0 as f16 (bits = 0x3C00)
    data[0] = 0x00;
    data[1] = 0x3C;
    // dmin = 0.0 as f16
    data[2] = 0x00;
    data[3] = 0x00;
    // scales: all zeros (results in zero output)
    // qs: all zeros

    let iq = InterleavedQ4K::from_q4k(&data).unwrap();
    let activations = vec![1.0f32; 256];
    let result = iq.dot(&activations);
    assert!(result.is_ok());
    // With zero scales and zero qs, result should be 0 or very small
    let val = result.unwrap();
    assert!(
        val.abs() < 0.1,
        "Dot product with zero data should be near zero, got {}",
        val
    );
}

// ============================================================================
// fused_q4_0_q8_0_dot_scalar
// ============================================================================

#[test]
fn test_fused_q4_0_q8_0_dot_scalar_zero() {
    // Q4_0 block: 18 bytes (2 scale + 16 quants)
    // All zeros
    let q4_data = vec![0u8; 18];
    let q8_scales = vec![1.0f32];
    let q8_quants = vec![0i8; 32];
    let result = fused_q4_0_q8_0_dot_scalar(&q4_data, &q8_scales, &q8_quants, 32);
    assert_eq!(result, 0.0);
}

#[test]
fn test_fused_q4_0_q8_0_dot_scalar_empty() {
    let result = fused_q4_0_q8_0_dot_scalar(&[], &[], &[], 0);
    assert_eq!(result, 0.0);
}

// ============================================================================
// fused_q4_0_q8_0_parallel_matvec
// ============================================================================

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_weight_too_small() {
    let weight_data = vec![0u8; 10]; // Too small
    let activations = vec![1.0f32; 32];
    let result = fused_q4_0_q8_0_parallel_matvec(&weight_data, &activations, 32, 2);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("too small"),
        "Error should mention too small: {}",
        err
    );
}

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_activation_mismatch() {
    // Need enough weight data for out_dim=1, in_dim=32 -> 1 block -> 18 bytes
    let weight_data = vec![0u8; 18];
    let activations = vec![1.0f32; 64]; // Wrong size
    let result = fused_q4_0_q8_0_parallel_matvec(&weight_data, &activations, 32, 1);
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(
        err.contains("Activation") || err.contains("activation"),
        "Error should mention activation mismatch: {}",
        err
    );
}

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_success() {
    // 1 row, 32 elements = 1 Q4_0 block (18 bytes)
    let weight_data = vec![0u8; 18];
    let activations = vec![0.0f32; 32];
    let result = fused_q4_0_q8_0_parallel_matvec(&weight_data, &activations, 32, 1);
    assert!(result.is_ok());
    let output = result.unwrap();
    assert_eq!(output.len(), 1);
}

// ============================================================================
// fused_q4_0_q8_0_parallel_matvec_into
// ============================================================================

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_into_weight_too_small() {
    let weight_data = vec![0u8; 10];
    let activations = vec![1.0f32; 32];
    let mut output = vec![0.0f32; 2];
    let result = fused_q4_0_q8_0_parallel_matvec_into(&weight_data, &activations, 32, &mut output);
    assert!(result.is_err());
}

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_into_activation_mismatch() {
    let weight_data = vec![0u8; 18];
    let activations = vec![1.0f32; 64]; // Wrong
    let mut output = vec![0.0f32; 1];
    let result = fused_q4_0_q8_0_parallel_matvec_into(&weight_data, &activations, 32, &mut output);
    assert!(result.is_err());
}

#[test]
fn test_fused_q4_0_q8_0_parallel_matvec_into_success() {
    let weight_data = vec![0u8; 18];
    let activations = vec![0.0f32; 32];
    let mut output = vec![0.0f32; 1];
    let result = fused_q4_0_q8_0_parallel_matvec_into(&weight_data, &activations, 32, &mut output);
    assert!(result.is_ok());
    assert_eq!(output.len(), 1);
}

// ============================================================================
// f16_to_f32_lut
// ============================================================================

#[test]
fn test_f16_to_f32_lut_zero() {
    let val = f16_to_f32_lut(0);
    assert_eq!(val, 0.0);
}

#[test]
fn test_f16_to_f32_lut_one() {
    // f16 1.0 = 0x3C00
    let val = f16_to_f32_lut(0x3C00);
    assert!((val - 1.0).abs() < 0.001, "Expected 1.0, got {}", val);
}

#[test]
fn test_f16_to_f32_lut_negative_one() {
    // f16 -1.0 = 0xBC00
    let val = f16_to_f32_lut(0xBC00);
    assert!((val - (-1.0)).abs() < 0.001, "Expected -1.0, got {}", val);
}

#[test]
fn test_f16_to_f32_lut_max() {
    // f16 max positive = 0x7BFF (~65504)
    let val = f16_to_f32_lut(0x7BFF);
    assert!(val > 65000.0, "Expected large value, got {}", val);
}

// ============================================================================
// SimdBackend
// ============================================================================

#[test]
fn test_simd_backend_display() {
    assert_eq!(format!("{}", SimdBackend::Avx2), "AVX2");
    assert_eq!(format!("{}", SimdBackend::Sse2), "SSE2");
    assert_eq!(format!("{}", SimdBackend::Neon), "NEON");
    assert_eq!(format!("{}", SimdBackend::Scalar), "Scalar");
}

#[test]
fn test_simd_backend_default() {
    let backend: SimdBackend = Default::default();
    assert_eq!(backend, SimdBackend::Scalar);
}

#[test]
fn test_simd_backend_eq() {
    assert_eq!(SimdBackend::Avx2, SimdBackend::Avx2);
    assert_ne!(SimdBackend::Avx2, SimdBackend::Sse2);
}

#[test]
fn test_simd_backend_clone() {
    let backend = SimdBackend::Avx2;
    let cloned = backend;
    assert_eq!(backend, cloned);
}

#[test]
fn test_simd_backend_debug() {
    let debug = format!("{:?}", SimdBackend::Avx2);
    assert!(debug.contains("Avx2"));
}

// ============================================================================
// DequantStats
// ============================================================================

#[test]
fn test_dequant_stats_default() {
    let stats: DequantStats = Default::default();
    assert_eq!(stats.blocks_processed, 0);
    assert_eq!(stats.bytes_processed, 0);
    assert_eq!(stats.simd_backend, SimdBackend::Scalar);
}

#[test]
fn test_dequant_stats_construction() {
    let stats = DequantStats {
        blocks_processed: 100,
        bytes_processed: 1800,
        simd_backend: SimdBackend::Avx2,
    };
    assert_eq!(stats.blocks_processed, 100);
    assert_eq!(stats.bytes_processed, 1800);
    assert_eq!(stats.simd_backend, SimdBackend::Avx2);
}

#[test]
fn test_dequant_stats_clone() {
    let stats = DequantStats {
        blocks_processed: 50,
        bytes_processed: 900,
        simd_backend: SimdBackend::Sse2,
    };
    let cloned = stats.clone();
    assert_eq!(cloned.blocks_processed, 50);
    assert_eq!(cloned.simd_backend, SimdBackend::Sse2);
}

#[test]
fn test_dequant_stats_debug() {
    let stats = DequantStats::default();
    let debug = format!("{:?}", stats);
    assert!(debug.contains("DequantStats"));
}

include!("tests_coverage_detect_simd.rs");
include!("q8_block_tests.rs");
include!("tests_coverage_04.rs");