trustformers 0.1.1

TrustformeRS - Rust port of Hugging Face Transformers
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#![allow(clippy::all)]
use proptest::prelude::*;
use std::collections::{HashMap, HashSet};
use trustformers::core::tensor::Tensor;
use trustformers::tokenizers::TokenizerWrapper;
use trustformers::*;

/// Fuzzing tests for TrustformeRS components
/// Tests robustness against unexpected inputs and edge cases

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

    /// Fuzz test for tensor operations
    #[test]
    fn fuzz_tensor_operations() {
        fn tensor_ops_test(
            shape: Vec<usize>,
            data: Vec<f32>,
        ) -> std::result::Result<(), TestCaseError> {
            if shape.is_empty() || shape.contains(&0) {
                return Ok(()); // Skip invalid shapes
            }

            let total_elements: usize = shape.iter().product();
            if total_elements > 1_000_000 || data.len() != total_elements {
                return Ok(()); // Skip extremely large tensors or mismatched data
            }

            let tensor = Tensor::from_slice(&data, &shape);

            match tensor {
                Ok(t) => {
                    // Test basic operations don't panic
                    let _ = t.shape();
                    let _ = t.data();

                    // Test mathematical operations
                    if let Ok(zeros) = Tensor::zeros(&shape) {
                        let _ = t.add(&zeros);
                        let _ = t.mul(&zeros);
                    }

                    // Test reshaping
                    if total_elements > 1 {
                        let _ = t.reshape(&[total_elements]);
                    }
                },
                Err(_) => {
                    // Expected for invalid inputs
                },
            }

            Ok(())
        }

        proptest!(|(
            shape in prop::collection::vec(1usize..100, 1..4),
            data_multiplier in 0.0f32..1000.0f32,
        )| {
            let total_elements: usize = shape.iter().product();
            let data: Vec<f32> = (0..total_elements)
                .map(|i| (i as f32) * data_multiplier / 1000.0)
                .collect();

            tensor_ops_test(shape, data)?;
        });
    }

    /// Fuzz test for tokenizer with random text inputs
    #[test]
    fn fuzz_tokenizer_random_text() {
        fn tokenize_test(text: String) -> std::result::Result<(), TestCaseError> {
            // Create a simple tokenizer for testing
            let vocab = HashMap::new();
            let merges = Vec::new();
            let bpe_tokenizer = trustformers::tokenizers::bpe::BPETokenizer::new(vocab, merges);
            let tokenizer = TokenizerWrapper::BPE(bpe_tokenizer);

            // Test tokenization doesn't panic on arbitrary text
            match tokenizer.encode(&text) {
                Ok(tokens) => {
                    // Verify tokens are valid
                    prop_assert!(tokens.input_ids.len() <= text.len() * 2 + 10); // Reasonable upper bound

                    // Test decoding
                    if let Ok(decoded) = tokenizer.decode(&tokens.input_ids) {
                        // Decoded text shouldn't be extremely longer than original
                        prop_assert!(decoded.len() <= text.len() * 3);
                    }
                },
                Err(_) => {
                    // Some invalid inputs may fail, which is acceptable
                },
            }

            Ok(())
        }

        proptest!(|(text in ".*{0,1000}")| {
            tokenize_test(text)?;
        });
    }

    /// Fuzz test for pipeline configuration
    #[test]
    fn fuzz_pipeline_config() {
        fn config_test(
            _device: String,
            batch_size: usize,
            max_length: usize,
            _temperature: f32,
        ) -> std::result::Result<(), TestCaseError> {
            // Test pipeline configuration with random parameters
            use trustformers::pipeline::PipelineOptions;

            let config = PipelineOptions {
                device: None, // Skip device for now due to type issues
                batch_size: Some(batch_size),
                max_length: Some(max_length),
                ..Default::default()
            };

            // Configuration creation should not panic
            prop_assert!(config.batch_size.unwrap_or(1) > 0);
            prop_assert!(config.max_length.unwrap_or(1) > 0);
            prop_assert!(config.truncation || !config.truncation);

            Ok(())
        }

        proptest!(|(
            device in prop::sample::select(vec!["cpu", "cuda", "mps", "auto"]),
            batch_size in 1usize..=128,
            max_length in 1usize..=8192,
            temperature in 0.0f32..=2.0f32,
        )| {
            config_test(device.to_string(), batch_size, max_length, temperature)?;
        });
    }

    /// Fuzz test for model metadata parsing
    #[test]
    fn fuzz_model_metadata() {
        fn metadata_test(
            metadata: HashMap<String, String>,
        ) -> std::result::Result<(), TestCaseError> {
            // Test metadata handling with arbitrary key-value pairs
            let metadata_json = serde_json::to_string(&metadata);

            match metadata_json {
                Ok(json_str) => {
                    // Test JSON roundtrip
                    if let Ok(parsed_metadata) =
                        serde_json::from_str::<HashMap<String, String>>(&json_str)
                    {
                        prop_assert_eq!(metadata.len(), parsed_metadata.len());
                    }
                },
                Err(_) => {
                    // Some metadata might not be serializable, which is fine
                },
            }

            Ok(())
        }

        proptest!(|(
            metadata in prop::collection::hash_map(
                "[a-zA-Z0-9_-]{1,50}",    // Keys
                ".*{0,200}",              // Values
                0..20                     // Size
            )
        )| {
            metadata_test(metadata)?;
        });
    }

    /// Fuzz test for error handling and recovery
    #[test]
    fn fuzz_error_handling() {
        fn error_test(
            error_message: String,
            _error_code: u32,
        ) -> std::result::Result<(), TestCaseError> {
            // Test error creation and handling
            let error = trustformers::error::TrustformersError::Pipeline {
                message: error_message.clone(),
                pipeline_type: "test-pipeline".to_string(),
                suggestion: Some("test suggestion".to_string()),
                recovery_actions: vec![],
            };

            // Error formatting should not panic
            let error_string = format!("{}", error);
            prop_assert!(!error_string.is_empty());

            // Error debug formatting should not panic
            let debug_string = format!("{:?}", error);
            prop_assert!(!debug_string.is_empty());

            Ok(())
        }

        proptest!(|(
            error_message in ".*{0,500}",
            error_code in 0u32..=10000u32,
        )| {
            error_test(error_message, error_code)?;
        });
    }

    /// Fuzz test for memory operations
    #[test]
    fn fuzz_memory_operations() {
        fn memory_test(
            allocation_size: usize,
            alignment: usize,
        ) -> std::result::Result<(), TestCaseError> {
            // Skip unreasonable sizes
            if allocation_size > 1_000_000 || alignment == 0 || !alignment.is_power_of_two() {
                return Ok(());
            }

            // Test memory pool operations
            use trustformers::memory_pool::{MemoryPool, MemoryPoolConfig};

            let config = MemoryPoolConfig {
                initial_size: allocation_size * 2,
                max_size: allocation_size * 10,
                alignment: 8,
                ..Default::default()
            };

            if let Ok(pool) = MemoryPool::new(config) {
                // Test allocation
                if let Ok(memory) = pool.allocate(allocation_size) {
                    // Test deallocation
                    let _ = pool.deallocate(memory);
                }
            }

            Ok(())
        }

        proptest!(|(
            allocation_size in 1usize..=100_000,
            alignment_exp in 0u8..=10,
        )| {
            let alignment = 1usize << alignment_exp;
            memory_test(allocation_size, alignment)?;
        });
    }

    /// Fuzz test for hub operations
    #[test]
    fn fuzz_hub_operations() {
        fn hub_test(
            model_id: String,
            revision: Option<String>,
        ) -> std::result::Result<(), TestCaseError> {
            // Test hub model cache checking
            use trustformers::hub::is_cached;

            // Cache check should not panic
            let _is_cached = is_cached(&model_id, revision.as_deref()).unwrap_or(false);

            Ok(())
        }

        proptest!(|(
            model_id in "[a-zA-Z0-9/_-]{1,100}",
            revision in prop::option::of("[a-zA-Z0-9._-]{0,50}"),
        )| {
            hub_test(model_id, revision)?;
        });
    }

    /// Fuzz test for configuration validation
    #[test]
    fn fuzz_config_validation() {
        fn config_validation_test(
            learning_rate: f64,
            batch_size: i32,
            max_steps: i64,
        ) -> std::result::Result<(), TestCaseError> {
            use trustformers::config_management::ConfigValidator;

            // Create test configuration
            let mut config = HashMap::new();
            config.insert("learning_rate".to_string(), learning_rate.to_string());
            config.insert("batch_size".to_string(), batch_size.to_string());
            config.insert("max_steps".to_string(), max_steps.to_string());

            let validator = ConfigValidator::new();
            let config_value = serde_json::to_value(&config).expect("operation failed in test");
            let schema = trustformers::config_management::ConfigSchema {
                name: "test_schema".to_string(),
                version: "1.0".to_string(),
                description: "Test schema for fuzzing".to_string(),
                fields: HashMap::new(),
                required_fields: HashSet::new(),
                conditional_requirements: Vec::new(),
            };

            // Validation should not panic
            let _result = validator.validate(&config_value, &schema);

            Ok(())
        }

        proptest!(|(
            learning_rate in -1.0f64..=1.0f64,
            batch_size in -100i32..=1000i32,
            max_steps in -1000i64..=100000i64,
        )| {
            config_validation_test(learning_rate, batch_size, max_steps)?;
        });
    }

    /// Fuzz test for streaming operations
    #[test]
    fn fuzz_streaming_operations() {
        fn streaming_test(
            chunk_size: usize,
            buffer_size: usize,
            timeout_ms: u64,
        ) -> std::result::Result<(), TestCaseError> {
            use trustformers::pipeline::streaming::StreamConfig;

            // Skip unreasonable values
            if chunk_size == 0 || buffer_size == 0 || timeout_ms > 60000 {
                return Ok(());
            }

            // Test stream configuration creation
            let config = StreamConfig {
                buffer_size,
                max_concurrent: 4,
                backpressure_threshold: 0.8,
                timeout_ms,
                enable_partial_results: true,
                enable_transformations: true,
                batch_size: Some(chunk_size),
                flush_interval_ms: 100,
            };

            // Configuration should be valid
            prop_assert!(config.buffer_size > 0);
            prop_assert!(config.batch_size.unwrap_or(0) > 0);
            prop_assert!(
                config.backpressure_threshold >= 0.0 && config.backpressure_threshold <= 1.0
            );

            Ok(())
        }

        proptest!(|(
            chunk_size in 1usize..=10000,
            buffer_size in 1usize..=10000,
            timeout_ms in 1u64..=5000,
        )| {
            streaming_test(chunk_size, buffer_size, timeout_ms)?;
        });
    }
}

/// Regression fuzzing tests
/// Tests for previously discovered issues to prevent regressions
#[cfg(test)]
mod regression_fuzz_tests {
    use super::*;

    /// Test for empty input handling regression
    #[test]
    fn fuzz_empty_inputs() {
        // Test various components with empty inputs
        let empty_text = "";
        let empty_vec: Vec<f32> = vec![];
        let _empty_shape: Vec<usize> = vec![];

        // Tokenizer should handle empty text gracefully
        let vocab = HashMap::new();
        let merges = Vec::new();
        let bpe_tokenizer = trustformers::tokenizers::bpe::BPETokenizer::new(vocab, merges);
        let tokenizer = TokenizerWrapper::BPE(bpe_tokenizer);
        {
            let _result = tokenizer.encode(empty_text);
        }

        // Tensor operations should handle empty data gracefully
        let _tensor_result = Tensor::from_slice(&empty_vec, &[0]);

        // Configuration should handle empty values
        let empty_config: HashMap<String, String> = HashMap::new();
        let _json_result = serde_json::to_string(&empty_config);
    }

    /// Test for unicode handling regression
    #[test]
    fn fuzz_unicode_inputs() {
        let long_text = "a".repeat(10000);
        let unicode_texts = vec![
            "Hello, 世界!",
            "🦀 Rust is great! 🚀",
            "Здравствуй мир",
            "مرحبا بالعالم",
            "नमस्ते दुनिया",
            "こんにちは世界",
            "",
            "\n\t\r",
            &long_text,
        ];

        for text in unicode_texts {
            // Test tokenization with unicode
            let vocab = HashMap::new();
            let merges = Vec::new();
            let bpe_tokenizer = trustformers::tokenizers::bpe::BPETokenizer::new(vocab, merges);
            let tokenizer = TokenizerWrapper::BPE(bpe_tokenizer);
            let _result = tokenizer.encode(text);

            // Test error message creation with unicode
            let error = trustformers::error::TrustformersError::Pipeline {
                message: text.to_string(),
                pipeline_type: "test-pipeline".to_string(),
                suggestion: Some("test suggestion".to_string()),
                recovery_actions: vec![],
            };
            let _formatted = format!("{}", error);
        }
    }

    /// Test for numerical edge cases regression
    #[test]
    fn fuzz_numerical_edge_cases() {
        let edge_values = vec![
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::NAN,
            f32::MIN,
            f32::MAX,
            0.0,
            -0.0,
            f32::EPSILON,
            1.0,
            -1.0,
        ];

        for value in edge_values {
            // Test tensor creation with edge values
            let data = vec![value; 10];
            let _tensor_result = Tensor::from_slice(&data, &[2, 5]);

            // Test configuration with edge values
            let mut config = HashMap::new();
            config.insert("temperature".to_string(), value.to_string());
            let _json_result = serde_json::to_string(&config);
        }
    }
}

/// Performance fuzzing tests
/// Tests for performance regression under various load conditions
#[cfg(test)]
mod performance_fuzz_tests {
    use super::*;
    use std::time::{Duration, Instant};

    /// Test that operations complete within reasonable time bounds
    #[test]
    fn fuzz_performance_bounds() {
        proptest!(|(
            size in 1usize..=1000,
            iterations in 1usize..=100,
        )| {
            let start = Instant::now();

            // Perform operations that should be reasonably fast
            for _ in 0..iterations {
                let data: Vec<f32> = (0..size).map(|i| i as f32).collect();
                if let Ok(tensor) = Tensor::from_slice(&data, &[size]) {
                    let _ = tensor.data();
                    let _ = tensor.shape();
                }
            }

            let elapsed = start.elapsed();
            prop_assert!(elapsed < Duration::from_secs(10), "Operations took too long: {:?}", elapsed);
        });
    }

    /// Test memory usage stays within bounds
    #[test]
    fn fuzz_memory_bounds() {
        use std::alloc::{GlobalAlloc, Layout, System};

        // Test that memory allocations are reasonable
        proptest!(|(
            allocation_count in 1usize..=100,
            allocation_size in 1usize..=1000,
        )| {
            let mut allocations = Vec::new();

            for _ in 0..allocation_count {
                if let Ok(layout) = Layout::array::<u8>(allocation_size) {
                    // This is just a test - in real code, use proper memory management
                    let ptr = unsafe { System.alloc(layout) };
                    if !ptr.is_null() {
                        allocations.push((ptr, layout));
                    }
                }
            }

            // Clean up allocations
            for (ptr, layout) in allocations {
                unsafe { System.dealloc(ptr, layout) };
            }

            prop_assert!(true); // Test that we can allocate and deallocate without issues
        });
    }
}