realizar 0.8.4

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

    #[test]
    fn test_apr_bytes_large_model_cov() {
        // Larger model to test serialization
        let apr = create_test_apr_transformer(64, 4, 100, 32);
        let bytes = GgufToAprConverter::to_apr_bytes(&apr).expect("serialize");

        // Should successfully serialize
        assert!(!bytes.is_empty());
        assert_eq!(&bytes[0..4], &MAGIC);
    }

    // =========================================================================
    // Coverage Tests: from_apr_bytes edge cases
    // =========================================================================

    #[test]
    fn test_from_apr_bytes_too_short_cov() {
        let bytes = vec![0u8; 10]; // Too short for header
        let result = GgufToAprConverter::from_apr_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_apr_bytes_bad_magic_cov() {
        let mut bytes = vec![0u8; 128];
        bytes[0..4].copy_from_slice(b"BADM"); // Wrong magic
        let result = GgufToAprConverter::from_apr_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_apr_bytes_wrong_version_cov() {
        let mut bytes = vec![0u8; 128];
        bytes[0..4].copy_from_slice(&MAGIC);
        bytes[4] = 99; // Unsupported version
        let result = GgufToAprConverter::from_apr_bytes(&bytes);
        assert!(result.is_err());
    }

    // =========================================================================
    // Coverage Tests: Q4K converter helper functions
    // =========================================================================

    #[test]
    fn test_q4k_converter_get_string_missing_cov() {
        use std::collections::HashMap;
        let metadata: HashMap<String, crate::gguf::GGUFValue> = HashMap::new();
        let result = GgufToAprQ4KConverter::get_string(&metadata, "nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_q4k_converter_get_u32_missing_cov() {
        use std::collections::HashMap;
        let metadata: HashMap<String, crate::gguf::GGUFValue> = HashMap::new();
        let result = GgufToAprQ4KConverter::get_u32(&metadata, "nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_q4k_converter_get_f32_missing_cov() {
        use std::collections::HashMap;
        let metadata: HashMap<String, crate::gguf::GGUFValue> = HashMap::new();
        let result = GgufToAprQ4KConverter::get_f32(&metadata, "nonexistent");
        assert!(result.is_none());
    }

    #[test]
    fn test_q4k_converter_get_u32_from_uint32_cov() {
        use crate::gguf::GGUFValue;
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("key".to_string(), GGUFValue::UInt32(256));
        let result = GgufToAprQ4KConverter::get_u32(&metadata, "key");
        assert_eq!(result, Some(256));
    }

    #[test]
    fn test_q4k_converter_get_u32_from_uint64_large_cov() {
        use crate::gguf::GGUFValue;
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("key".to_string(), GGUFValue::UInt64(1024));
        let result = GgufToAprQ4KConverter::get_u32(&metadata, "key");
        assert_eq!(result, Some(1024));
    }

    #[test]
    fn test_q4k_converter_get_f32_from_float32_cov() {
        use crate::gguf::GGUFValue;
        let mut metadata = std::collections::HashMap::new();
        metadata.insert("key".to_string(), GGUFValue::Float32(1.5));
        let result = GgufToAprQ4KConverter::get_f32(&metadata, "key");
        assert!(result.is_some());
        assert!((result.expect("operation failed") - 1.5).abs() < 0.0001);
    }

    // =========================================================================
    // PMAT-107: infer_rope_type Tests
    // =========================================================================

    #[test]
    fn test_pmat_107_infer_rope_type_qwen2_is_neox() {
        // Qwen2 architecture should use NEOX style (type 2)
        let metadata: std::collections::HashMap<String, crate::gguf::GGUFValue> =
            std::collections::HashMap::new();
        let result = GgufToAprQ4KConverter::infer_rope_type("qwen2", &metadata);
        assert_eq!(result, 2, "Qwen2 should use NEOX style (rope_type=2)");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_llama_is_norm() {
        // LLaMA architecture should use NORM style (type 0)
        let metadata: std::collections::HashMap<String, crate::gguf::GGUFValue> =
            std::collections::HashMap::new();
        let result = GgufToAprQ4KConverter::infer_rope_type("llama", &metadata);
        assert_eq!(result, 0, "LLaMA should use NORM style (rope_type=0)");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_phi3_is_neox() {
        // Phi3 architecture should use NEOX style (type 2)
        let metadata: std::collections::HashMap<String, crate::gguf::GGUFValue> =
            std::collections::HashMap::new();
        let result = GgufToAprQ4KConverter::infer_rope_type("phi3", &metadata);
        assert_eq!(result, 2, "Phi3 should use NEOX style (rope_type=2)");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_gemma_is_neox() {
        // Gemma architecture should use NEOX style (type 2)
        let metadata: std::collections::HashMap<String, crate::gguf::GGUFValue> =
            std::collections::HashMap::new();
        let result = GgufToAprQ4KConverter::infer_rope_type("gemma", &metadata);
        assert_eq!(result, 2, "Gemma should use NEOX style (rope_type=2)");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_scaling_yarn_overrides() {
        // rope.scaling.type=yarn should override architecture inference
        use crate::gguf::GGUFValue;
        let mut metadata = std::collections::HashMap::new();
        metadata.insert(
            "llama.rope.scaling.type".to_string(),
            GGUFValue::String("yarn".to_string()),
        );
        let result = GgufToAprQ4KConverter::infer_rope_type("llama", &metadata);
        assert_eq!(result, 2, "yarn scaling type should override to NEOX style");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_scaling_linear_is_norm() {
        // rope.scaling.type=linear should use NORM style
        use crate::gguf::GGUFValue;
        let mut metadata = std::collections::HashMap::new();
        metadata.insert(
            "qwen2.rope.scaling.type".to_string(),
            GGUFValue::String("linear".to_string()),
        );
        let result = GgufToAprQ4KConverter::infer_rope_type("qwen2", &metadata);
        assert_eq!(result, 0, "linear scaling type should use NORM style");
    }

    #[test]
    fn test_pmat_107_infer_rope_type_unknown_defaults_to_norm() {
        // Unknown architecture should default to NORM style (type 0)
        let metadata: std::collections::HashMap<String, crate::gguf::GGUFValue> =
            std::collections::HashMap::new();
        let result = GgufToAprQ4KConverter::infer_rope_type("unknown_arch", &metadata);
        assert_eq!(result, 0, "Unknown arch should default to NORM style");
    }

    // =========================================================================
    // Coverage Tests: ConversionStats
    // =========================================================================

    #[test]
    fn test_conversion_stats_fields_cov() {
        let stats = ConversionStats {
            total_parameters: 1000000,
            memory_bytes_f32: 4000000,
            num_layers: 12,
            hidden_dim: 768,
            vocab_size: 32000,
            architecture: "llama".to_string(),
        };
        assert_eq!(stats.total_parameters, 1000000);
        assert_eq!(stats.memory_bytes_f32, 4000000);
        assert_eq!(stats.num_layers, 12);
        assert_eq!(stats.hidden_dim, 768);
        assert_eq!(stats.vocab_size, 32000);
        assert_eq!(stats.architecture, "llama");
    }

    #[test]
    fn test_conversion_stats_zero_values_cov() {
        let stats = ConversionStats {
            total_parameters: 0,
            memory_bytes_f32: 0,
            num_layers: 0,
            hidden_dim: 0,
            vocab_size: 0,
            architecture: String::new(),
        };
        assert_eq!(stats.total_parameters, 0);
        assert_eq!(stats.memory_bytes_f32, 0);
        assert_eq!(stats.num_layers, 0);
    }

    #[test]
    fn test_conversion_stats_debug_clone_cov() {
        let stats = ConversionStats {
            total_parameters: 500000,
            memory_bytes_f32: 2000000,
            num_layers: 6,
            hidden_dim: 512,
            vocab_size: 10000,
            architecture: "phi2".to_string(),
        };
        let debug = format!("{:?}", stats);
        assert!(debug.contains("ConversionStats"));

        let cloned = stats.clone();
        assert_eq!(cloned.total_parameters, stats.total_parameters);
    }

    // =========================================================================
    // Coverage Tests: AprTransformerConfig
    // =========================================================================

    #[test]
    fn test_apr_transformer_config_partial_eq_cov() {
        let config1 = create_test_apr_transformer(4, 1, 10, 8).config;
        let config2 = create_test_apr_transformer(4, 1, 10, 8).config;
        assert_eq!(config1, config2);
    }

    #[test]
    fn test_apr_transformer_config_not_equal_cov() {
        let config1 = create_test_apr_transformer(4, 1, 10, 8).config;
        let config2 = create_test_apr_transformer(8, 2, 20, 16).config;
        assert_ne!(config1, config2);
    }

    // =========================================================================
    // Coverage Tests: RawTensor struct
    // =========================================================================

    #[test]
    fn test_raw_tensor_debug_cov() {
        let tensor = RawTensor {
            name: "test_tensor".to_string(),
            data: vec![1, 2, 3, 4],
            shape: vec![2, 2],
            dtype: 0, // F32
        };
        let debug_str = format!("{:?}", tensor);
        assert!(debug_str.contains("test_tensor"));
        assert!(debug_str.contains("shape"));
    }

    #[test]
    fn test_raw_tensor_clone_cov() {
        let tensor = RawTensor {
            name: "cloneable".to_string(),
            data: vec![10, 20, 30],
            shape: vec![3],
            dtype: 1, // F16
        };
        let cloned = tensor.clone();
        assert_eq!(cloned.name, tensor.name);
        assert_eq!(cloned.data, tensor.data);
        assert_eq!(cloned.shape, tensor.shape);
        assert_eq!(cloned.dtype, tensor.dtype);
    }

    #[test]
    fn test_raw_tensor_empty_data_cov() {
        let tensor = RawTensor {
            name: "empty".to_string(),
            data: vec![],
            shape: vec![0],
            dtype: 0,
        };
        assert!(tensor.data.is_empty());
        assert_eq!(tensor.shape, vec![0]);
    }

    #[test]
    fn test_raw_tensor_large_dtype_cov() {
        let tensor = RawTensor {
            name: "q4k".to_string(),
            data: vec![0u8; 144], // Q4_K: 256 elements = 144 bytes
            shape: vec![256],
            dtype: 12, // Q4_K
        };
        assert_eq!(tensor.dtype, 12);
        assert_eq!(tensor.data.len(), 144);
    }

    #[test]
    fn test_raw_tensor_multidim_shape_cov() {
        let tensor = RawTensor {
            name: "3d_tensor".to_string(),
            data: vec![0u8; 24],
            shape: vec![2, 3, 4],
            dtype: 0,
        };
        assert_eq!(tensor.shape.len(), 3);
        let total: usize = tensor.shape.iter().product();
        assert_eq!(total, 24);
    }

    // =========================================================================
    // Coverage Tests: Q4KConversionStats struct
    // =========================================================================

    #[test]
    fn test_q4k_conversion_stats_all_fields_cov() {
        let stats = Q4KConversionStats {
            tensor_count: 200,
            q4k_tensor_count: 150,
            total_bytes: 5_000_000,
            architecture: "mistral".to_string(),
            num_layers: 24,
            hidden_size: 3072,
        };
        assert_eq!(stats.tensor_count, 200);
        assert_eq!(stats.q4k_tensor_count, 150);
        assert_eq!(stats.total_bytes, 5_000_000);
        assert_eq!(stats.architecture, "mistral");
        assert_eq!(stats.num_layers, 24);
        assert_eq!(stats.hidden_size, 3072);
    }

    #[test]
    fn test_q4k_conversion_stats_zero_values_cov() {
        let stats = Q4KConversionStats {
            tensor_count: 0,
            q4k_tensor_count: 0,
            total_bytes: 0,
            architecture: String::new(),
            num_layers: 0,
            hidden_size: 0,
        };
        assert_eq!(stats.tensor_count, 0);
        assert_eq!(stats.total_bytes, 0);
        assert!(stats.architecture.is_empty());
    }

    // =========================================================================
    // Coverage Tests: GgufToAprConverter::stats
    // =========================================================================

    #[test]
    fn test_stats_function_cov() {
        let apr = create_test_apr_transformer(16, 4, 1000, 64);
        let stats = GgufToAprConverter::stats(&apr);

        assert_eq!(stats.num_layers, 4);
        assert_eq!(stats.hidden_dim, 16);
        assert_eq!(stats.vocab_size, 1000);
        assert!(stats.total_parameters > 0);
        assert!(stats.memory_bytes_f32 > 0);
    }

    #[test]
    fn test_stats_memory_calculations_cov() {
        let apr = create_test_apr_transformer(32, 2, 500, 128);
        let stats = GgufToAprConverter::stats(&apr);

        // Memory should be related to parameters
        assert!(stats.memory_mb() > 0.0);
        assert!(stats.memory_gb() < stats.memory_mb());
        assert!(stats.parameters_m() > 0.0);
    }

    // =========================================================================
    // Coverage Tests: from_apr_bytes additional error paths
    // =========================================================================

    #[test]
    fn test_from_apr_bytes_truncated_data_cov() {
        // Create valid header but truncate before data section
        let apr = create_test_apr_transformer(4, 1, 10, 8);
        let mut bytes = GgufToAprConverter::to_apr_bytes(&apr).expect("serialize");

        // Truncate to only keep header and partial metadata
        bytes.truncate(100);

        let result = GgufToAprConverter::from_apr_bytes(&bytes);
        assert!(result.is_err());
    }

    #[test]
    fn test_from_apr_bytes_invalid_metadata_json_cov() {
        let mut bytes = vec![0u8; 256];
        bytes[0..4].copy_from_slice(&MAGIC);
        bytes[4] = 2; // v2
        bytes[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 tensor
        bytes[12..20].copy_from_slice(&64u64.to_le_bytes()); // metadata offset
        bytes[20..24].copy_from_slice(&50u32.to_le_bytes()); // metadata size = 50
        bytes[24..32].copy_from_slice(&120u64.to_le_bytes()); // tensor index offset
        bytes[32..40].copy_from_slice(&200u64.to_le_bytes()); // data offset

        // Invalid JSON metadata (just garbage bytes)
        for i in 64..114 {
            bytes[i] = b'X';
        }

        let result = GgufToAprConverter::from_apr_bytes(&bytes);
        // Should error due to invalid metadata JSON
        assert!(result.is_err());
    }

    // =========================================================================
    // Coverage Tests: to_apr_bytes edge cases
    // =========================================================================

    #[test]
    fn test_to_apr_bytes_empty_layers_cov() {
        let apr = create_test_apr_transformer(4, 0, 10, 8);
        let bytes = GgufToAprConverter::to_apr_bytes(&apr).expect("serialize");

        // Should still serialize with valid header
        assert_eq!(&bytes[0..4], &MAGIC);
        assert!(bytes.len() > HEADER_SIZE);
    }

    #[test]
    fn test_to_apr_bytes_large_vocab_cov() {
        let apr = create_test_apr_transformer(8, 1, 50000, 32);
        let bytes = GgufToAprConverter::to_apr_bytes(&apr).expect("serialize");

        assert!(!bytes.is_empty());
        assert_eq!(&bytes[0..4], &MAGIC);
    }

    #[test]
    fn test_to_apr_bytes_small_dims_cov() {
        // Minimum viable transformer
        let apr = create_test_apr_transformer(2, 1, 4, 2);
        let bytes = GgufToAprConverter::to_apr_bytes(&apr).expect("serialize");

        assert!(!bytes.is_empty());
    }