realizar 0.8.6

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

    // ========================================================================
    // ChatMessage Tests
    // ========================================================================

    #[test]
    fn test_chat_message_new() {
        let msg = ChatMessage::new("user", "Hello");
        assert_eq!(msg.role, "user");
        assert_eq!(msg.content, "Hello");
    }

    #[test]
    fn test_chat_message_constructors() {
        let sys = ChatMessage::system("sys");
        assert_eq!(sys.role, "system");

        let user = ChatMessage::user("usr");
        assert_eq!(user.role, "user");

        let asst = ChatMessage::assistant("asst");
        assert_eq!(asst.role, "assistant");
    }

    #[test]
    fn test_chat_message_serde_roundtrip() {
        let msg = ChatMessage::user("Hello, world!");
        let json = serde_json::to_string(&msg).expect("serialize");
        let restored: ChatMessage = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(msg, restored);
    }

    // ========================================================================
    // Format Detection Tests
    // ========================================================================

    #[test]
    fn test_detect_chatml() {
        assert_eq!(
            detect_format_from_name("Qwen2-0.5B-Instruct"),
            TemplateFormat::ChatML
        );
        assert_eq!(
            detect_format_from_name("OpenHermes-2.5"),
            TemplateFormat::ChatML
        );
        assert_eq!(
            detect_format_from_name("Yi-6B-Chat"),
            TemplateFormat::ChatML
        );
    }

    #[test]
    fn test_detect_zephyr() {
        assert_eq!(
            detect_format_from_name("TinyLlama-1.1B-Chat"),
            TemplateFormat::Zephyr
        );
        assert_eq!(
            detect_format_from_name("zephyr-7b-beta"),
            TemplateFormat::Zephyr
        );
        assert_eq!(
            detect_format_from_name("stablelm-3b-4e1t"),
            TemplateFormat::Zephyr
        );
    }

    #[test]
    fn test_detect_llama2() {
        assert_eq!(
            detect_format_from_name("vicuna-7b-v1.5"),
            TemplateFormat::Llama2
        );
        assert_eq!(
            detect_format_from_name("Llama-2-7B-Chat"),
            TemplateFormat::Llama2
        );
    }

    #[test]
    fn test_detect_mistral() {
        assert_eq!(
            detect_format_from_name("Mistral-7B-Instruct"),
            TemplateFormat::Mistral
        );
        assert_eq!(
            detect_format_from_name("Mixtral-8x7B"),
            TemplateFormat::Mistral
        );
    }

    #[test]
    fn test_detect_phi() {
        assert_eq!(detect_format_from_name("phi-2"), TemplateFormat::Phi);
        assert_eq!(detect_format_from_name("phi-3-mini"), TemplateFormat::Phi);
    }

    #[test]
    fn test_detect_alpaca() {
        assert_eq!(detect_format_from_name("alpaca-7b"), TemplateFormat::Alpaca);
    }

    #[test]
    fn test_detect_raw_fallback() {
        assert_eq!(
            detect_format_from_name("unknown-model"),
            TemplateFormat::Raw
        );
    }

    #[test]
    fn test_detection_deterministic() {
        let name = "TinyLlama-1.1B-Chat";
        let format1 = detect_format_from_name(name);
        let format2 = detect_format_from_name(name);
        assert_eq!(format1, format2);
    }

    #[test]
    fn test_detection_case_insensitive() {
        assert_eq!(
            detect_format_from_name("TINYLLAMA-1.1B-CHAT"),
            TemplateFormat::Zephyr
        );
        assert_eq!(
            detect_format_from_name("qwen2-0.5b-instruct"),
            TemplateFormat::ChatML
        );
    }

    // ========================================================================
    // ChatML Template Tests
    // ========================================================================

    #[test]
    fn test_chatml_format_message() {
        let template = ChatMLTemplate::new();
        let result = template
            .format_message("user", "Hello!")
            .expect("operation failed");
        assert_eq!(result, "<|im_start|>user\nHello!<|im_end|>\n");
    }

    #[test]
    fn test_chatml_format_conversation() {
        let template = ChatMLTemplate::new();
        let messages = vec![
            ChatMessage::system("You are helpful."),
            ChatMessage::user("Hello!"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("<|im_start|>system"));
        assert!(output.contains("You are helpful."));
        assert!(output.contains("<|im_start|>user"));
        assert!(output.contains("Hello!"));
        assert!(output.ends_with("<|im_start|>assistant\n"));
    }

    #[test]
    fn test_chatml_special_tokens() {
        let template = ChatMLTemplate::new();
        assert_eq!(
            template.special_tokens().im_start_token,
            Some("<|im_start|>".to_string())
        );
        assert_eq!(
            template.special_tokens().im_end_token,
            Some("<|im_end|>".to_string())
        );
    }

    // ========================================================================
    // LLaMA2 Template Tests
    // ========================================================================

    #[test]
    fn test_llama2_format_conversation() {
        let template = Llama2Template::new();
        let messages = vec![
            ChatMessage::system("You are helpful."),
            ChatMessage::user("Hello!"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.starts_with("<s>"));
        assert!(output.contains("[INST]"));
        assert!(output.contains("<<SYS>>"));
        assert!(output.contains("You are helpful."));
        assert!(output.contains("<</SYS>>"));
        assert!(output.contains("Hello!"));
        assert!(output.contains("[/INST]"));
    }

    #[test]
    fn test_llama2_multi_turn() {
        let template = Llama2Template::new();
        let messages = vec![
            ChatMessage::user("Hello!"),
            ChatMessage::assistant("Hi there!"),
            ChatMessage::user("How are you?"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("Hello!"));
        assert!(output.contains("Hi there!"));
        assert!(output.contains("How are you?"));
        assert!(output.contains("</s>"));
    }

    // ========================================================================
    // Zephyr Template Tests (TinyLlama, Zephyr, StableLM)
    // ========================================================================

    #[test]
    fn test_zephyr_format_conversation() {
        let template = ZephyrTemplate::new();
        let messages = vec![
            ChatMessage::system("You are helpful."),
            ChatMessage::user("Hello!"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        // Zephyr format: <|role|>\ncontent</s>\n
        assert!(output.contains("<|system|>\n"));
        assert!(output.contains("You are helpful."));
        assert!(output.contains("</s>\n"));
        assert!(output.contains("<|user|>\n"));
        assert!(output.contains("Hello!"));
        assert!(output.ends_with("<|assistant|>\n"));
    }

    #[test]
    fn test_zephyr_multi_turn() {
        let template = ZephyrTemplate::new();
        let messages = vec![
            ChatMessage::user("Hello!"),
            ChatMessage::assistant("Hi there!"),
            ChatMessage::user("How are you?"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("<|user|>\nHello!</s>\n"));
        assert!(output.contains("<|assistant|>\nHi there!</s>\n"));
        assert!(output.contains("<|user|>\nHow are you?</s>\n"));
        assert!(output.ends_with("<|assistant|>\n"));
    }

    #[test]
    fn test_zephyr_supports_system() {
        let template = ZephyrTemplate::new();
        assert!(template.supports_system_prompt());
    }

    // ========================================================================
    // Mistral Template Tests
    // ========================================================================

    #[test]
    fn test_mistral_no_system_prompt() {
        let template = MistralTemplate::new();
        assert!(!template.supports_system_prompt());

        let messages = vec![
            ChatMessage::system("System prompt"),
            ChatMessage::user("Hello!"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        // System prompt should be ignored
        assert!(!output.contains("System prompt"));
        assert!(output.contains("[INST]"));
        assert!(output.contains("Hello!"));
    }

    // ========================================================================
    // Phi Template Tests
    // ========================================================================

    #[test]
    fn test_phi_format() {
        let template = PhiTemplate::new();
        let messages = vec![ChatMessage::user("Hello!")];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("Instruct: Hello!"));
        assert!(output.ends_with("Output:"));
    }

    // ========================================================================
    // Alpaca Template Tests
    // ========================================================================

    #[test]
    fn test_alpaca_format() {
        let template = AlpacaTemplate::new();
        let messages = vec![ChatMessage::user("Hello!")];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("### Instruction:"));
        assert!(output.contains("Hello!"));
        assert!(output.ends_with("### Response:\n"));
    }

    // ========================================================================
    // Raw Template Tests
    // ========================================================================

    #[test]
    fn test_raw_format() {
        let template = RawTemplate::new();
        let messages = vec![
            ChatMessage::system("System"),
            ChatMessage::user("User"),
            ChatMessage::assistant("Assistant"),
        ];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert_eq!(output, "SystemUserAssistant");
    }

    // ========================================================================
    // format_messages Tests
    // ========================================================================

    #[test]
    fn test_format_messages_with_model() {
        let messages = vec![ChatMessage::user("Hello!")];

        let output = format_messages(&messages, Some("Qwen2-0.5B")).expect("operation failed");
        assert!(output.contains("<|im_start|>"));

        // TinyLlama uses Zephyr format, NOT Llama2
        let output = format_messages(&messages, Some("TinyLlama")).expect("operation failed");
        assert!(output.contains("<|user|>"));
        assert!(output.contains("<|assistant|>"));
    }

    #[test]
    fn test_format_messages_without_model() {
        let messages = vec![ChatMessage::user("Hello!")];
        let output = format_messages(&messages, None).expect("operation failed");
        assert_eq!(output, "Hello!");
    }

    // ========================================================================
    // Edge Cases
    // ========================================================================

    #[test]
    fn test_empty_conversation() {
        let template = ChatMLTemplate::new();
        let messages: Vec<ChatMessage> = vec![];
        let result = template.format_conversation(&messages);
        assert!(result.is_ok());
    }

    #[test]
    fn test_unicode_preserved() {
        let template = ChatMLTemplate::new();
        let messages = vec![ChatMessage::user("Hello! 你好 مرحبا 🎉")];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");

        assert!(output.contains("你好"));
        assert!(output.contains("مرحبا"));
        assert!(output.contains("🎉"));
    }

    #[test]
    fn test_long_content() {
        let template = ChatMLTemplate::new();
        let long_content = "x".repeat(10_000);
        let messages = vec![ChatMessage::user(&long_content)];
        let result = template.format_conversation(&messages);
        assert!(result.is_ok());
    }

    #[test]
    fn test_whitespace_preserved() {
        let template = ChatMLTemplate::new();
        let messages = vec![ChatMessage::user("  content with spaces  ")];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");
        assert!(output.contains("  content with spaces  "));
    }

    #[test]
    fn test_multiline_content() {
        let template = ChatMLTemplate::new();
        let multiline = "Line 1\nLine 2\nLine 3";
        let messages = vec![ChatMessage::user(multiline)];
        let output = template
            .format_conversation(&messages)
            .expect("operation failed");
        assert!(output.contains("Line 1\nLine 2\nLine 3"));
    }

    #[test]
    fn test_custom_role() {
        let template = ChatMLTemplate::new();
        let messages = vec![
            ChatMessage::new("tool", "Function result: 42"),
            ChatMessage::user("What was the result?"),
        ];
        let result = template.format_conversation(&messages);
        assert!(result.is_ok());
        let output = result.expect("operation failed");
        assert!(output.contains("tool"));
        assert!(output.contains("Function result: 42"));
    }

    // ========================================================================
    // Security Tests
    // ========================================================================

    #[test]
    fn test_template_injection_prevention() {
        let template = ChatMLTemplate::new();
        let messages = vec![ChatMessage::user("{% for i in range(10) %}X{% endfor %}")];
        let result = template.format_conversation(&messages);
        assert!(result.is_ok());
        // Jinja syntax should appear as literal content
        let output = result.expect("operation failed");
        assert!(output.contains("{% for i in range(10) %}"));
    }