ruvllm 2.2.1

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
#![allow(
    clippy::all,
    unused_imports,
    unused_variables,
    dead_code,
    unused_mut,
    unused_assignments,
    non_camel_case_types,
    clippy::approx_constant,
    unexpected_cfgs,
    unused_must_use,
    unused_parens
)]
//! Integration tests for v2.1 model architectures (Phi-3, Gemma-2)
//!
//! Tests cover:
//! - Model configuration creation and validation
//! - Chat template formatting
//! - Sliding window attention
//! - Logit soft capping
//! - Grouped Query Attention (GQA)
//! - RoPE (Rotary Position Embedding) configurations

// =============================================================================
// Model Configuration Types
// =============================================================================

/// Attention type for different model architectures
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AttentionType {
    /// Multi-Head Attention (standard)
    MHA,
    /// Grouped Query Attention (fewer KV heads)
    GQA,
    /// Multi-Query Attention (single KV head)
    MQA,
}

/// RoPE scaling configuration
#[derive(Debug, Clone, PartialEq)]
pub struct RopeScaling {
    pub scaling_type: RopeScalingType,
    pub factor: f32,
    pub low_freq_factor: Option<f32>,
    pub high_freq_factor: Option<f32>,
    pub original_max_position_embeddings: Option<usize>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RopeScalingType {
    Linear,
    Dynamic,
    Yarn,
    Longrope,
    Su,
}

impl Default for RopeScaling {
    fn default() -> Self {
        Self {
            scaling_type: RopeScalingType::Linear,
            factor: 1.0,
            low_freq_factor: None,
            high_freq_factor: None,
            original_max_position_embeddings: None,
        }
    }
}

// =============================================================================
// Phi-3 Configuration
// =============================================================================

/// Configuration for Phi-3 family models
#[derive(Debug, Clone)]
pub struct Phi3Config {
    pub vocab_size: usize,
    pub hidden_size: usize,
    pub intermediate_size: usize,
    pub num_hidden_layers: usize,
    pub num_attention_heads: usize,
    pub num_key_value_heads: usize,
    pub hidden_act: String,
    pub max_position_embeddings: usize,
    pub original_max_position_embeddings: usize,
    pub rms_norm_eps: f64,
    pub rope_theta: f64,
    pub rope_scaling: Option<RopeScaling>,
    pub sliding_window: Option<usize>,
    pub attention_bias: bool,
    pub attention_dropout: f32,
    pub bos_token_id: u32,
    pub eos_token_id: u32,
}

impl Phi3Config {
    /// Create configuration for Phi-3-mini (3.8B parameters)
    pub fn phi3_mini() -> Self {
        Self {
            vocab_size: 32064,
            hidden_size: 3072,
            intermediate_size: 8192,
            num_hidden_layers: 32,
            num_attention_heads: 32,
            num_key_value_heads: 32,
            hidden_act: "silu".to_string(),
            max_position_embeddings: 131072,
            original_max_position_embeddings: 4096,
            rms_norm_eps: 1e-5,
            rope_theta: 10000.0,
            rope_scaling: Some(RopeScaling {
                scaling_type: RopeScalingType::Longrope,
                factor: 1.0,
                low_freq_factor: Some(1.0),
                high_freq_factor: Some(4.0),
                original_max_position_embeddings: Some(4096),
            }),
            sliding_window: None,
            attention_bias: false,
            attention_dropout: 0.0,
            bos_token_id: 1,
            eos_token_id: 32000,
        }
    }

    /// Create configuration for Phi-3-small (7B parameters)
    pub fn phi3_small() -> Self {
        Self {
            vocab_size: 100352,
            hidden_size: 4096,
            intermediate_size: 14336,
            num_hidden_layers: 32,
            num_attention_heads: 32,
            num_key_value_heads: 8, // GQA with 4:1 ratio
            hidden_act: "silu".to_string(),
            max_position_embeddings: 131072,
            original_max_position_embeddings: 8192,
            rms_norm_eps: 1e-5,
            rope_theta: 10000.0,
            rope_scaling: Some(RopeScaling {
                scaling_type: RopeScalingType::Longrope,
                factor: 1.0,
                low_freq_factor: Some(1.0),
                high_freq_factor: Some(4.0),
                original_max_position_embeddings: Some(8192),
            }),
            sliding_window: None,
            attention_bias: false,
            attention_dropout: 0.0,
            bos_token_id: 100257,
            eos_token_id: 100257,
        }
    }

    /// Create configuration for Phi-3-medium (14B parameters)
    pub fn phi3_medium() -> Self {
        Self {
            vocab_size: 32064,
            hidden_size: 5120,
            intermediate_size: 17920,
            num_hidden_layers: 40,
            num_attention_heads: 40,
            num_key_value_heads: 10, // GQA with 4:1 ratio
            hidden_act: "silu".to_string(),
            max_position_embeddings: 131072,
            original_max_position_embeddings: 4096,
            rms_norm_eps: 1e-5,
            rope_theta: 10000.0,
            rope_scaling: Some(RopeScaling {
                scaling_type: RopeScalingType::Longrope,
                factor: 1.0,
                low_freq_factor: Some(1.0),
                high_freq_factor: Some(4.0),
                original_max_position_embeddings: Some(4096),
            }),
            sliding_window: None,
            attention_bias: false,
            attention_dropout: 0.0,
            bos_token_id: 1,
            eos_token_id: 32000,
        }
    }

    /// Get attention type based on head configuration
    pub fn attention_type(&self) -> AttentionType {
        if self.num_key_value_heads == 1 {
            AttentionType::MQA
        } else if self.num_key_value_heads < self.num_attention_heads {
            AttentionType::GQA
        } else {
            AttentionType::MHA
        }
    }

    /// Calculate head dimension
    pub fn head_dim(&self) -> usize {
        self.hidden_size / self.num_attention_heads
    }

    /// Calculate KV groups for GQA
    pub fn num_kv_groups(&self) -> usize {
        self.num_attention_heads / self.num_key_value_heads
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<(), String> {
        if self.hidden_size % self.num_attention_heads != 0 {
            return Err("hidden_size must be divisible by num_attention_heads".to_string());
        }
        if self.num_attention_heads % self.num_key_value_heads != 0 {
            return Err("num_attention_heads must be divisible by num_key_value_heads".to_string());
        }
        if self.vocab_size == 0 {
            return Err("vocab_size must be greater than 0".to_string());
        }
        Ok(())
    }
}

// =============================================================================
// Gemma-2 Configuration
// =============================================================================

/// Configuration for Gemma-2 family models
#[derive(Debug, Clone)]
pub struct Gemma2Config {
    pub vocab_size: usize,
    pub hidden_size: usize,
    pub intermediate_size: usize,
    pub num_hidden_layers: usize,
    pub num_attention_heads: usize,
    pub num_key_value_heads: usize,
    pub head_dim: usize,
    pub hidden_act: String,
    pub hidden_activation: String,
    pub max_position_embeddings: usize,
    pub rms_norm_eps: f64,
    pub rope_theta: f64,
    pub attention_bias: bool,
    pub attention_dropout: f32,
    /// Sliding window size for local attention layers
    pub sliding_window: usize,
    /// Query pre-attention scalar
    pub query_pre_attn_scalar: f32,
    /// Logit soft capping value for attention
    pub attn_logit_softcapping: f32,
    /// Logit soft capping value for final logits
    pub final_logit_softcapping: f32,
    pub bos_token_id: u32,
    pub eos_token_id: u32,
    pub pad_token_id: u32,
}

impl Gemma2Config {
    /// Create configuration for Gemma-2-2B
    pub fn gemma2_2b() -> Self {
        Self {
            vocab_size: 256000,
            hidden_size: 2304,
            intermediate_size: 9216,
            num_hidden_layers: 26,
            num_attention_heads: 8,
            num_key_value_heads: 4,
            head_dim: 256,
            hidden_act: "gelu_pytorch_tanh".to_string(),
            hidden_activation: "gelu_pytorch_tanh".to_string(),
            max_position_embeddings: 8192,
            rms_norm_eps: 1e-6,
            rope_theta: 10000.0,
            attention_bias: false,
            attention_dropout: 0.0,
            sliding_window: 4096,
            query_pre_attn_scalar: 256.0,
            attn_logit_softcapping: 50.0,
            final_logit_softcapping: 30.0,
            bos_token_id: 2,
            eos_token_id: 1,
            pad_token_id: 0,
        }
    }

    /// Create configuration for Gemma-2-9B
    pub fn gemma2_9b() -> Self {
        Self {
            vocab_size: 256000,
            hidden_size: 3584,
            intermediate_size: 14336,
            num_hidden_layers: 42,
            num_attention_heads: 16,
            num_key_value_heads: 8,
            head_dim: 256,
            hidden_act: "gelu_pytorch_tanh".to_string(),
            hidden_activation: "gelu_pytorch_tanh".to_string(),
            max_position_embeddings: 8192,
            rms_norm_eps: 1e-6,
            rope_theta: 10000.0,
            attention_bias: false,
            attention_dropout: 0.0,
            sliding_window: 4096,
            query_pre_attn_scalar: 256.0,
            attn_logit_softcapping: 50.0,
            final_logit_softcapping: 30.0,
            bos_token_id: 2,
            eos_token_id: 1,
            pad_token_id: 0,
        }
    }

    /// Create configuration for Gemma-2-27B
    pub fn gemma2_27b() -> Self {
        Self {
            vocab_size: 256000,
            hidden_size: 4608,
            intermediate_size: 36864,
            num_hidden_layers: 46,
            num_attention_heads: 32,
            num_key_value_heads: 16,
            head_dim: 128,
            hidden_act: "gelu_pytorch_tanh".to_string(),
            hidden_activation: "gelu_pytorch_tanh".to_string(),
            max_position_embeddings: 8192,
            rms_norm_eps: 1e-6,
            rope_theta: 10000.0,
            attention_bias: false,
            attention_dropout: 0.0,
            sliding_window: 4096,
            query_pre_attn_scalar: 128.0,
            attn_logit_softcapping: 50.0,
            final_logit_softcapping: 30.0,
            bos_token_id: 2,
            eos_token_id: 1,
            pad_token_id: 0,
        }
    }

    /// Get attention type based on head configuration
    pub fn attention_type(&self) -> AttentionType {
        if self.num_key_value_heads == 1 {
            AttentionType::MQA
        } else if self.num_key_value_heads < self.num_attention_heads {
            AttentionType::GQA
        } else {
            AttentionType::MHA
        }
    }

    /// Calculate KV groups for GQA
    pub fn num_kv_groups(&self) -> usize {
        self.num_attention_heads / self.num_key_value_heads
    }

    /// Check if a layer uses sliding window attention
    pub fn uses_sliding_window(&self, layer_idx: usize) -> bool {
        // Gemma-2 uses alternating global and local attention
        // Even layers use global, odd layers use sliding window
        layer_idx % 2 == 1
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<(), String> {
        if self.num_attention_heads % self.num_key_value_heads != 0 {
            return Err("num_attention_heads must be divisible by num_key_value_heads".to_string());
        }
        if self.vocab_size == 0 {
            return Err("vocab_size must be greater than 0".to_string());
        }
        if self.attn_logit_softcapping <= 0.0 {
            return Err("attn_logit_softcapping must be positive".to_string());
        }
        if self.final_logit_softcapping <= 0.0 {
            return Err("final_logit_softcapping must be positive".to_string());
        }
        Ok(())
    }
}

// =============================================================================
// Chat Template System
// =============================================================================

/// Chat message role
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    System,
    User,
    Assistant,
}

/// Chat message
#[derive(Debug, Clone)]
pub struct ChatMessage {
    pub role: Role,
    pub content: String,
}

impl ChatMessage {
    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: Role::System,
            content: content.into(),
        }
    }

    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            content: content.into(),
        }
    }

    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            content: content.into(),
        }
    }
}

/// Chat template for formatting conversations
pub trait ChatTemplate {
    /// Format a list of messages into a prompt string
    fn format(&self, messages: &[ChatMessage], add_generation_prompt: bool) -> String;

    /// Get the template name
    fn name(&self) -> &str;
}

/// Phi-3 chat template
pub struct Phi3ChatTemplate;

impl ChatTemplate for Phi3ChatTemplate {
    fn format(&self, messages: &[ChatMessage], add_generation_prompt: bool) -> String {
        let mut result = String::new();

        for message in messages {
            match message.role {
                Role::System => {
                    result.push_str(&format!("<|system|>\n{}<|end|>\n", message.content));
                }
                Role::User => {
                    result.push_str(&format!("<|user|>\n{}<|end|>\n", message.content));
                }
                Role::Assistant => {
                    result.push_str(&format!("<|assistant|>\n{}<|end|>\n", message.content));
                }
            }
        }

        if add_generation_prompt {
            result.push_str("<|assistant|>\n");
        }

        result
    }

    fn name(&self) -> &str {
        "phi3"
    }
}

/// Gemma chat template
pub struct GemmaChatTemplate;

impl ChatTemplate for GemmaChatTemplate {
    fn format(&self, messages: &[ChatMessage], add_generation_prompt: bool) -> String {
        let mut result = String::new();

        for message in messages {
            match message.role {
                Role::System => {
                    // Gemma doesn't have a system role, prepend to first user message
                    result.push_str(&format!("<start_of_turn>user\n{}", message.content));
                }
                Role::User => {
                    if result.ends_with("<start_of_turn>user\n") {
                        // System message was added, append to it
                        result.push_str(&format!("\n\n{}<end_of_turn>\n", message.content));
                    } else {
                        result.push_str(&format!(
                            "<start_of_turn>user\n{}<end_of_turn>\n",
                            message.content
                        ));
                    }
                }
                Role::Assistant => {
                    result.push_str(&format!(
                        "<start_of_turn>model\n{}<end_of_turn>\n",
                        message.content
                    ));
                }
            }
        }

        if add_generation_prompt {
            result.push_str("<start_of_turn>model\n");
        }

        result
    }

    fn name(&self) -> &str {
        "gemma"
    }
}

/// ChatML template (used by many models)
pub struct ChatMLTemplate;

impl ChatTemplate for ChatMLTemplate {
    fn format(&self, messages: &[ChatMessage], add_generation_prompt: bool) -> String {
        let mut result = String::new();

        for message in messages {
            let role = match message.role {
                Role::System => "system",
                Role::User => "user",
                Role::Assistant => "assistant",
            };
            result.push_str(&format!(
                "<|im_start|>{}\n{}<|im_end|>\n",
                role, message.content
            ));
        }

        if add_generation_prompt {
            result.push_str("<|im_start|>assistant\n");
        }

        result
    }

    fn name(&self) -> &str {
        "chatml"
    }
}

// =============================================================================
// Sliding Window Attention
// =============================================================================

/// Sliding window attention mask generator
pub struct SlidingWindowMask {
    window_size: usize,
}

impl SlidingWindowMask {
    pub fn new(window_size: usize) -> Self {
        Self { window_size }
    }

    /// Generate attention mask for a given sequence length
    /// Returns a 2D mask where true = attend, false = mask
    pub fn generate_mask(&self, seq_len: usize) -> Vec<Vec<bool>> {
        let mut mask = vec![vec![false; seq_len]; seq_len];

        for i in 0..seq_len {
            let start = if i >= self.window_size {
                i - self.window_size + 1
            } else {
                0
            };
            for j in start..=i {
                mask[i][j] = true;
            }
        }

        mask
    }

    /// Check if position j is visible from position i
    pub fn is_visible(&self, i: usize, j: usize) -> bool {
        j <= i && i - j < self.window_size
    }

    /// Get the effective context length for a position
    pub fn effective_context(&self, position: usize) -> usize {
        std::cmp::min(position + 1, self.window_size)
    }
}

// =============================================================================
// Logit Soft Capping
// =============================================================================

/// Logit soft capping implementation
pub struct LogitSoftCap {
    cap: f32,
}

impl LogitSoftCap {
    pub fn new(cap: f32) -> Self {
        assert!(cap > 0.0, "Cap must be positive");
        Self { cap }
    }

    /// Apply soft capping to a single logit
    /// Formula: cap * tanh(logit / cap)
    pub fn apply(&self, logit: f32) -> f32 {
        self.cap * (logit / self.cap).tanh()
    }

    /// Apply soft capping to a slice of logits
    pub fn apply_to_slice(&self, logits: &mut [f32]) {
        for logit in logits.iter_mut() {
            *logit = self.apply(*logit);
        }
    }

    /// Check if a logit would be capped
    pub fn would_cap(&self, logit: f32) -> bool {
        logit.abs() > self.cap * 0.9 // Approximately where tanh starts saturating
    }
}

// =============================================================================
// RoPE (Rotary Position Embedding)
// =============================================================================

/// RoPE implementation for position encoding
pub struct RoPE {
    dim: usize,
    theta: f64,
    max_seq_len: usize,
    cos_cache: Vec<Vec<f32>>,
    sin_cache: Vec<Vec<f32>>,
}

impl RoPE {
    pub fn new(dim: usize, theta: f64, max_seq_len: usize) -> Self {
        let mut rope = Self {
            dim,
            theta,
            max_seq_len,
            cos_cache: Vec::new(),
            sin_cache: Vec::new(),
        };
        rope.build_cache();
        rope
    }

    fn build_cache(&mut self) {
        self.cos_cache = vec![vec![0.0; self.dim / 2]; self.max_seq_len];
        self.sin_cache = vec![vec![0.0; self.dim / 2]; self.max_seq_len];

        for pos in 0..self.max_seq_len {
            for i in 0..self.dim / 2 {
                let freq = 1.0 / self.theta.powf(2.0 * i as f64 / self.dim as f64);
                let angle = pos as f64 * freq;
                self.cos_cache[pos][i] = angle.cos() as f32;
                self.sin_cache[pos][i] = angle.sin() as f32;
            }
        }
    }

    /// Apply RoPE to query/key vectors at a given position
    pub fn apply(&self, x: &[f32], position: usize) -> Vec<f32> {
        assert!(position < self.max_seq_len, "Position exceeds max_seq_len");
        assert_eq!(x.len(), self.dim, "Input dimension mismatch");

        let mut result = vec![0.0; self.dim];

        for i in 0..self.dim / 2 {
            let cos = self.cos_cache[position][i];
            let sin = self.sin_cache[position][i];

            let x0 = x[2 * i];
            let x1 = x[2 * i + 1];

            result[2 * i] = x0 * cos - x1 * sin;
            result[2 * i + 1] = x0 * sin + x1 * cos;
        }

        result
    }

    /// Get the dimension
    pub fn dim(&self) -> usize {
        self.dim
    }
}

// =============================================================================
// Tests
// =============================================================================

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

    // -------------------------------------------------------------------------
    // Phi-3 Configuration Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_phi3_config_creation() {
        let config = Phi3Config::phi3_mini();
        assert_eq!(config.hidden_size, 3072);
        assert_eq!(config.num_hidden_layers, 32);
        assert_eq!(config.vocab_size, 32064);
    }

    #[test]
    fn test_phi3_mini_dimensions() {
        let config = Phi3Config::phi3_mini();
        assert_eq!(config.hidden_size, 3072);
        assert_eq!(config.intermediate_size, 8192);
        assert_eq!(config.num_attention_heads, 32);
        assert_eq!(config.num_key_value_heads, 32);
        assert_eq!(config.head_dim(), 96); // 3072 / 32
    }

    #[test]
    fn test_phi3_small_gqa() {
        let config = Phi3Config::phi3_small();
        assert_eq!(config.attention_type(), AttentionType::GQA);
        assert_eq!(config.num_kv_groups(), 4); // 32 / 8
    }

    #[test]
    fn test_phi3_medium_gqa() {
        let config = Phi3Config::phi3_medium();
        assert_eq!(config.attention_type(), AttentionType::GQA);
        assert_eq!(config.num_kv_groups(), 4); // 40 / 10
        assert_eq!(config.head_dim(), 128); // 5120 / 40
    }

    #[test]
    fn test_phi3_mini_mha() {
        let config = Phi3Config::phi3_mini();
        assert_eq!(config.attention_type(), AttentionType::MHA);
        assert_eq!(config.num_kv_groups(), 1);
    }

    #[test]
    fn test_phi3_rope_scaling() {
        let config = Phi3Config::phi3_mini();
        let rope_scaling = config.rope_scaling.as_ref().unwrap();
        assert_eq!(rope_scaling.scaling_type, RopeScalingType::Longrope);
        assert_eq!(rope_scaling.low_freq_factor, Some(1.0));
        assert_eq!(rope_scaling.high_freq_factor, Some(4.0));
    }

    #[test]
    fn test_phi3_config_validation() {
        let config = Phi3Config::phi3_mini();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_phi3_invalid_config() {
        let mut config = Phi3Config::phi3_mini();
        config.num_key_value_heads = 3; // Not a divisor of 32
        assert!(config.validate().is_err());
    }

    // -------------------------------------------------------------------------
    // Gemma-2 Configuration Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_gemma2_config_creation() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.hidden_size, 3584);
        assert_eq!(config.head_dim, 256);
        assert_eq!(config.attn_logit_softcapping, 50.0);
    }

    #[test]
    fn test_gemma2_2b_dimensions() {
        let config = Gemma2Config::gemma2_2b();
        assert_eq!(config.hidden_size, 2304);
        assert_eq!(config.num_hidden_layers, 26);
        assert_eq!(config.num_attention_heads, 8);
        assert_eq!(config.num_key_value_heads, 4);
        assert_eq!(config.vocab_size, 256000);
    }

    #[test]
    fn test_gemma2_9b_dimensions() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.hidden_size, 3584);
        assert_eq!(config.num_hidden_layers, 42);
        assert_eq!(config.num_attention_heads, 16);
        assert_eq!(config.num_key_value_heads, 8);
    }

    #[test]
    fn test_gemma2_27b_dimensions() {
        let config = Gemma2Config::gemma2_27b();
        assert_eq!(config.hidden_size, 4608);
        assert_eq!(config.num_hidden_layers, 46);
        assert_eq!(config.num_attention_heads, 32);
        assert_eq!(config.num_key_value_heads, 16);
        assert_eq!(config.head_dim, 128);
    }

    #[test]
    fn test_gemma2_gqa() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.attention_type(), AttentionType::GQA);
        assert_eq!(config.num_kv_groups(), 2); // 16 / 8
    }

    #[test]
    fn test_gemma2_sliding_window() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.sliding_window, 4096);

        // Alternating layers
        assert!(!config.uses_sliding_window(0)); // Global
        assert!(config.uses_sliding_window(1)); // Local (sliding window)
        assert!(!config.uses_sliding_window(2)); // Global
        assert!(config.uses_sliding_window(3)); // Local
    }

    #[test]
    fn test_gemma2_logit_softcapping_values() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.attn_logit_softcapping, 50.0);
        assert_eq!(config.final_logit_softcapping, 30.0);
    }

    #[test]
    fn test_gemma2_query_pre_attn_scalar() {
        let config = Gemma2Config::gemma2_9b();
        assert_eq!(config.query_pre_attn_scalar, 256.0);
        assert_eq!(config.query_pre_attn_scalar, config.head_dim as f32);
    }

    #[test]
    fn test_gemma2_config_validation() {
        let config = Gemma2Config::gemma2_9b();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_gemma2_invalid_softcapping() {
        let mut config = Gemma2Config::gemma2_9b();
        config.attn_logit_softcapping = 0.0;
        assert!(config.validate().is_err());
    }

    // -------------------------------------------------------------------------
    // Chat Template Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_phi3_chat_template_single_user() {
        let template = Phi3ChatTemplate;
        let messages = vec![ChatMessage::user("Hello, how are you?")];

        let result = template.format(&messages, true);

        assert!(result.contains("<|user|>"));
        assert!(result.contains("Hello, how are you?"));
        assert!(result.contains("<|end|>"));
        assert!(result.ends_with("<|assistant|>\n"));
    }

    #[test]
    fn test_phi3_chat_template_with_system() {
        let template = Phi3ChatTemplate;
        let messages = vec![
            ChatMessage::system("You are a helpful assistant."),
            ChatMessage::user("What is 2+2?"),
        ];

        let result = template.format(&messages, true);

        assert!(result.contains("<|system|>"));
        assert!(result.contains("You are a helpful assistant."));
        assert!(result.contains("<|user|>"));
        assert!(result.contains("What is 2+2?"));
    }

    #[test]
    fn test_phi3_chat_template_conversation() {
        let template = Phi3ChatTemplate;
        let messages = vec![
            ChatMessage::user("Hello"),
            ChatMessage::assistant("Hi there!"),
            ChatMessage::user("How are you?"),
        ];

        let result = template.format(&messages, true);

        assert!(result.contains("<|assistant|>\nHi there!<|end|>"));
    }

    #[test]
    fn test_gemma_chat_template_single_user() {
        let template = GemmaChatTemplate;
        let messages = vec![ChatMessage::user("Hello, how are you?")];

        let result = template.format(&messages, true);

        assert!(result.contains("<start_of_turn>user"));
        assert!(result.contains("Hello, how are you?"));
        assert!(result.contains("<end_of_turn>"));
        assert!(result.ends_with("<start_of_turn>model\n"));
    }

    #[test]
    fn test_gemma_chat_template_with_system() {
        let template = GemmaChatTemplate;
        let messages = vec![
            ChatMessage::system("You are a helpful assistant."),
            ChatMessage::user("What is 2+2?"),
        ];

        let result = template.format(&messages, true);

        // System message should be prepended to user message
        assert!(result.contains("You are a helpful assistant."));
        assert!(result.contains("What is 2+2?"));
    }

    #[test]
    fn test_gemma_chat_template_uses_model_role() {
        let template = GemmaChatTemplate;
        let messages = vec![ChatMessage::user("Hello"), ChatMessage::assistant("Hi!")];

        let result = template.format(&messages, false);

        assert!(result.contains("<start_of_turn>model\nHi!<end_of_turn>"));
    }

    #[test]
    fn test_chatml_template() {
        let template = ChatMLTemplate;
        let messages = vec![
            ChatMessage::system("You are helpful."),
            ChatMessage::user("Hello"),
        ];

        let result = template.format(&messages, true);

        assert!(result.contains("<|im_start|>system\nYou are helpful.<|im_end|>"));
        assert!(result.contains("<|im_start|>user\nHello<|im_end|>"));
        assert!(result.ends_with("<|im_start|>assistant\n"));
    }

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

        let result = template.format(&messages, false);

        assert!(!result.ends_with("<|assistant|>\n"));
    }

    // -------------------------------------------------------------------------
    // Sliding Window Attention Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_sliding_window_mask_basic() {
        let window = SlidingWindowMask::new(3);
        let mask = window.generate_mask(5);

        // Position 0 can only see itself
        assert!(mask[0][0]);

        // Position 2 can see positions 0, 1, 2
        assert!(mask[2][0]);
        assert!(mask[2][1]);
        assert!(mask[2][2]);

        // Position 4 can see positions 2, 3, 4 (not 0, 1)
        assert!(!mask[4][0]);
        assert!(!mask[4][1]);
        assert!(mask[4][2]);
        assert!(mask[4][3]);
        assert!(mask[4][4]);
    }

    #[test]
    fn test_sliding_window_visibility() {
        let window = SlidingWindowMask::new(4096);

        // Within window
        assert!(window.is_visible(100, 50));
        assert!(window.is_visible(4095, 0));

        // Just outside window
        assert!(!window.is_visible(4096, 0));
        assert!(window.is_visible(4096, 1));
    }

    #[test]
    fn test_sliding_window_effective_context() {
        let window = SlidingWindowMask::new(4096);

        assert_eq!(window.effective_context(0), 1);
        assert_eq!(window.effective_context(100), 101);
        assert_eq!(window.effective_context(4095), 4096);
        assert_eq!(window.effective_context(5000), 4096);
        assert_eq!(window.effective_context(10000), 4096);
    }

    #[test]
    fn test_sliding_window_causal() {
        let window = SlidingWindowMask::new(100);

        // Cannot see future positions
        assert!(!window.is_visible(5, 10));
        assert!(!window.is_visible(0, 1));
    }

    // -------------------------------------------------------------------------
    // Logit Soft Capping Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_logit_softcap_basic() {
        let cap = LogitSoftCap::new(50.0);

        // Small values pass through approximately unchanged
        let small = cap.apply(1.0);
        assert!((small - 1.0).abs() < 0.1);

        // Large values get capped
        let large = cap.apply(100.0);
        assert!(large < 50.0);
        assert!(large > 45.0); // tanh(2) ≈ 0.964
    }

    #[test]
    fn test_logit_softcap_symmetry() {
        let cap = LogitSoftCap::new(50.0);

        let pos = cap.apply(30.0);
        let neg = cap.apply(-30.0);

        assert!((pos + neg).abs() < 0.001);
    }

    #[test]
    fn test_logit_softcap_bounds() {
        let cap = LogitSoftCap::new(50.0);

        // Even extreme values stay bounded
        // tanh(1000/50) = tanh(20) is essentially 1.0
        // So result = 50 * 1.0 = 50.0 (at the cap, not below)
        let extreme = cap.apply(1000.0);
        assert!(extreme <= 50.0);
        assert!(extreme > 49.9); // Very close to cap

        let neg_extreme = cap.apply(-1000.0);
        assert!(neg_extreme >= -50.0);
        assert!(neg_extreme < -49.9);
    }

    #[test]
    fn test_logit_softcap_slice() {
        let cap = LogitSoftCap::new(30.0);
        let mut logits = vec![1.0, 50.0, -50.0, 100.0];

        cap.apply_to_slice(&mut logits);

        assert!((logits[0] - 1.0).abs() < 0.1);
        assert!(logits[1] < 30.0);
        assert!(logits[2] > -30.0);
        assert!(logits[3] < 30.0);
    }

    #[test]
    fn test_logit_softcap_would_cap() {
        let cap = LogitSoftCap::new(50.0);

        assert!(!cap.would_cap(10.0));
        assert!(!cap.would_cap(30.0));
        assert!(cap.would_cap(50.0));
        assert!(cap.would_cap(100.0));
        assert!(cap.would_cap(-60.0));
    }

    #[test]
    fn test_gemma2_attention_softcap() {
        let config = Gemma2Config::gemma2_9b();
        let cap = LogitSoftCap::new(config.attn_logit_softcapping);

        // Simulate attention scores
        let scores = vec![10.0, 25.0, 60.0, -40.0, 100.0];
        let mut capped = scores.clone();
        cap.apply_to_slice(&mut capped);

        // All should be within bounds
        for &score in &capped {
            assert!(score.abs() < config.attn_logit_softcapping);
        }
    }

    #[test]
    fn test_gemma2_final_softcap() {
        let config = Gemma2Config::gemma2_9b();
        let cap = LogitSoftCap::new(config.final_logit_softcapping);

        let extreme_logit = 1000.0;
        let capped = cap.apply(extreme_logit);

        // tanh approaches 1.0 for large inputs, so capped approaches the cap value
        assert!(capped <= config.final_logit_softcapping);
        assert!(capped > config.final_logit_softcapping - 0.1);
    }

    // -------------------------------------------------------------------------
    // RoPE Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_rope_creation() {
        let rope = RoPE::new(64, 10000.0, 2048);
        assert_eq!(rope.dim(), 64);
    }

    #[test]
    fn test_rope_apply_preserves_length() {
        let rope = RoPE::new(64, 10000.0, 2048);
        let input = vec![1.0; 64];

        let output = rope.apply(&input, 0);
        assert_eq!(output.len(), 64);
    }

    #[test]
    fn test_rope_position_zero() {
        let rope = RoPE::new(64, 10000.0, 2048);
        let input = vec![1.0; 64];

        let output = rope.apply(&input, 0);

        // At position 0, cos(0)=1 and sin(0)=0
        // So output should be close to input
        for i in 0..32 {
            assert!((output[2 * i] - input[2 * i]).abs() < 0.01);
        }
    }

    #[test]
    fn test_rope_different_positions() {
        let rope = RoPE::new(64, 10000.0, 2048);
        let input = vec![1.0; 64];

        let out0 = rope.apply(&input, 0);
        let out1 = rope.apply(&input, 1);
        let out100 = rope.apply(&input, 100);

        // Different positions should give different outputs
        assert!(out0 != out1);
        assert!(out1 != out100);
    }

    #[test]
    fn test_rope_norm_preservation() {
        let rope = RoPE::new(64, 10000.0, 2048);
        let input: Vec<f32> = (0..64).map(|i| (i as f32) * 0.1).collect();

        let output = rope.apply(&input, 50);

        // RoPE is a rotation, so it should preserve the norm of each 2D pair
        for i in 0..32 {
            let in_norm = (input[2 * i].powi(2) + input[2 * i + 1].powi(2)).sqrt();
            let out_norm = (output[2 * i].powi(2) + output[2 * i + 1].powi(2)).sqrt();
            assert!((in_norm - out_norm).abs() < 0.0001);
        }
    }

    // -------------------------------------------------------------------------
    // Integration Tests
    // -------------------------------------------------------------------------

    #[test]
    fn test_phi3_full_pipeline_setup() {
        let config = Phi3Config::phi3_mini();
        let template = Phi3ChatTemplate;
        let rope = RoPE::new(
            config.head_dim(),
            config.rope_theta,
            config.max_position_embeddings,
        );

        // Validate config
        assert!(config.validate().is_ok());

        // Format a message
        let messages = vec![
            ChatMessage::system("You are a helpful AI."),
            ChatMessage::user("Hello!"),
        ];
        let prompt = template.format(&messages, true);
        assert!(!prompt.is_empty());

        // RoPE is ready
        assert_eq!(rope.dim(), config.head_dim());
    }

    #[test]
    fn test_gemma2_full_pipeline_setup() {
        let config = Gemma2Config::gemma2_9b();
        let template = GemmaChatTemplate;
        let sliding_window = SlidingWindowMask::new(config.sliding_window);
        let attn_cap = LogitSoftCap::new(config.attn_logit_softcapping);
        let final_cap = LogitSoftCap::new(config.final_logit_softcapping);

        // Validate config
        assert!(config.validate().is_ok());

        // Format a message
        let messages = vec![ChatMessage::user("What is the capital of France?")];
        let prompt = template.format(&messages, true);
        assert!(!prompt.is_empty());

        // Sliding window is ready
        assert_eq!(
            sliding_window.effective_context(10000),
            config.sliding_window
        );

        // Soft caps are ready
        assert!(attn_cap.apply(100.0) < config.attn_logit_softcapping);
        assert!(final_cap.apply(100.0) < config.final_logit_softcapping);
    }

    #[test]
    fn test_model_comparison() {
        let phi3 = Phi3Config::phi3_mini();
        let gemma2 = Gemma2Config::gemma2_9b();

        // Different vocab sizes
        assert!(gemma2.vocab_size > phi3.vocab_size);

        // Both use GeLU variants
        assert!(phi3.hidden_act.contains("silu") || phi3.hidden_act.contains("gelu"));
        assert!(gemma2.hidden_act.contains("gelu"));

        // Gemma-2 has soft capping, Phi-3 doesn't need it
        assert!(gemma2.attn_logit_softcapping > 0.0);
    }

    #[test]
    fn test_attention_type_detection() {
        // MHA
        let phi3_mini = Phi3Config::phi3_mini();
        assert_eq!(phi3_mini.attention_type(), AttentionType::MHA);

        // GQA
        let phi3_small = Phi3Config::phi3_small();
        assert_eq!(phi3_small.attention_type(), AttentionType::GQA);

        let gemma2 = Gemma2Config::gemma2_9b();
        assert_eq!(gemma2.attention_type(), AttentionType::GQA);
    }
}