trustformers-models 0.1.1

Model implementations for TrustformeRS
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
//! # Mathematics-Specialized Models
//!
//! This module provides specialized model configurations and implementations
//! optimized for mathematical reasoning, symbolic computation, and formula understanding.
//!
//! ## Features
//!
//! - **Mathematical Notation**: Enhanced tokenization for mathematical symbols and LaTeX
//! - **Step-by-Step Reasoning**: Structured generation for mathematical proofs and solutions
//! - **Formula Understanding**: Specialized attention patterns for mathematical expressions
//! - **Multi-Modal Math**: Support for text, equations, and mathematical diagrams
//! - **Theorem Proving**: Integration with formal verification systems
//! - **Scientific Computing**: Optimized for scientific and engineering calculations
//!
//! ## Supported Model Families
//!
//! ### MathLlama Family
//! - Mathematical reasoning versions of LLaMA models
//! - Enhanced mathematical vocabulary and training
//! - Step-by-step solution generation
//!
//! ### PaLM-Math Family
//! - Google's PaLM models fine-tuned for mathematics
//! - Chain-of-thought reasoning capabilities
//! - Multi-step problem solving
//!
//! ### DeepSeek-Math Family
//! - DeepSeek models specialized for mathematical reasoning
//! - Formal proof generation capabilities
//! - Scientific computation optimization
//!
//! ### MAmmoTH Family
//! - Large-scale mathematical reasoning models
//! - Multi-domain mathematical understanding
//! - Competition-level problem solving
//!
//! ## Example Usage
//!
//! ```rust
//! use trustformers_models::math_specialized::{MathSpecializedConfig, MathSpecializedForCausalLM};
//!
//! // Create a mathematical reasoning model
//! let config = MathSpecializedConfig::math_llama_7b();
//! let model = MathSpecializedForCausalLM::new(config)?;
//!
//! // Solve a mathematical problem
//! let problem = "Find the derivative of f(x) = x^2 + 3x + 1";
//! let solution = model.solve_step_by_step(problem)?;
//! ```

use serde::{Deserialize, Serialize};
use trustformers_core::errors::{invalid_config, Result};
use trustformers_core::tensor::Tensor;
use trustformers_core::{Config, Layer, Model};

#[cfg(feature = "llama")]
use crate::llama::{LlamaConfig, LlamaModel};

/// Configuration for mathematics-specialized models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MathSpecializedConfig {
    /// Base model configuration
    pub base_config: LlamaConfig,
    /// Mathematical vocabulary size (including symbols)
    pub math_vocab_size: Option<usize>,
    /// Whether to use step-by-step reasoning
    pub step_by_step_reasoning: bool,
    /// Support for mathematical notation
    pub math_notation_support: bool,
    /// LaTeX rendering capabilities
    pub latex_support: bool,
    /// Formula parsing and understanding
    pub formula_parsing: bool,
    /// Symbolic computation capabilities
    pub symbolic_computation: bool,
    /// Mathematical domains supported
    pub supported_domains: Vec<MathDomain>,
    /// Reasoning strategies
    pub reasoning_strategies: Vec<ReasoningStrategy>,
    /// Mathematical special tokens
    pub math_tokens: MathSpecialTokens,
    /// Context length optimized for math problems
    pub math_context_length: usize,
    /// Whether to use mathematical attention patterns
    pub math_attention_patterns: bool,
    /// Model variant type
    pub model_variant: MathModelVariant,
    /// Chain-of-thought configuration
    pub chain_of_thought: ChainOfThoughtConfig,
}

/// Mathematical domains supported by the model
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MathDomain {
    /// Elementary mathematics
    Elementary,
    /// Algebra and pre-calculus
    Algebra,
    /// Calculus and analysis
    Calculus,
    /// Linear algebra
    LinearAlgebra,
    /// Discrete mathematics
    DiscreteMath,
    /// Statistics and probability
    Statistics,
    /// Geometry and topology
    Geometry,
    /// Number theory
    NumberTheory,
    /// Mathematical logic
    Logic,
    /// Applied mathematics
    Applied,
    /// Physics and engineering math
    Physics,
    /// Computer science mathematics
    ComputerScience,
    /// Competition mathematics
    Competition,
}

/// Reasoning strategies for mathematical problem solving
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ReasoningStrategy {
    /// Step-by-step analytical reasoning
    StepByStep,
    /// Chain-of-thought reasoning
    ChainOfThought,
    /// Working backwards from conclusion
    BackwardReasoning,
    /// Case-by-case analysis
    CaseAnalysis,
    /// Proof by contradiction
    ProofByContradiction,
    /// Mathematical induction
    Induction,
    /// Constructive proof
    Constructive,
    /// Analogical reasoning
    Analogical,
    /// Visual/geometric reasoning
    Visual,
    /// Symbolic manipulation
    Symbolic,
}

/// Mathematical special tokens
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MathSpecialTokens {
    /// Step separator token
    pub step_separator: String,
    /// Solution start token
    pub solution_start: String,
    /// Solution end token
    pub solution_end: String,
    /// Equation start token
    pub equation_start: String,
    /// Equation end token
    pub equation_end: String,
    /// Proof start token
    pub proof_start: String,
    /// Proof end token
    pub proof_end: String,
    /// Therefore symbol
    pub therefore: String,
    /// Because symbol
    pub because: String,
    /// QED symbol
    pub qed: String,
}

/// Chain-of-thought configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainOfThoughtConfig {
    /// Enable chain-of-thought reasoning
    pub enabled: bool,
    /// Maximum reasoning steps
    pub max_steps: usize,
    /// Step verification enabled
    pub step_verification: bool,
    /// Confidence scoring for each step
    pub confidence_scoring: bool,
    /// Backtracking on errors
    pub backtrack_on_error: bool,
}

/// Mathematical model variant types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MathModelVariant {
    /// Mathematical reasoning version of LLaMA
    MathLlama,
    /// DeepSeek-Math variant
    DeepSeekMath,
    /// PaLM-Math variant
    PalmMath,
    /// MAmmoTH variant
    Mammoth,
    /// Minerva variant (Google)
    Minerva,
    /// Mathematical Qwen variant
    QwenMath,
    /// CodeT5-Math variant
    CodeT5Math,
}

impl Default for MathSpecialTokens {
    fn default() -> Self {
        Self {
            step_separator: "<step>".to_string(),
            solution_start: "<solution>".to_string(),
            solution_end: "</solution>".to_string(),
            equation_start: "<eq>".to_string(),
            equation_end: "</eq>".to_string(),
            proof_start: "<proof>".to_string(),
            proof_end: "</proof>".to_string(),
            therefore: "".to_string(),
            because: "".to_string(),
            qed: "".to_string(),
        }
    }
}

impl Default for ChainOfThoughtConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_steps: 20,
            step_verification: true,
            confidence_scoring: true,
            backtrack_on_error: true,
        }
    }
}

impl Default for MathSpecializedConfig {
    fn default() -> Self {
        Self {
            base_config: LlamaConfig::default(),
            math_vocab_size: None,
            step_by_step_reasoning: true,
            math_notation_support: true,
            latex_support: true,
            formula_parsing: true,
            symbolic_computation: true,
            supported_domains: vec![
                MathDomain::Elementary,
                MathDomain::Algebra,
                MathDomain::Calculus,
                MathDomain::LinearAlgebra,
                MathDomain::Statistics,
                MathDomain::Geometry,
            ],
            reasoning_strategies: vec![
                ReasoningStrategy::StepByStep,
                ReasoningStrategy::ChainOfThought,
                ReasoningStrategy::CaseAnalysis,
                ReasoningStrategy::Symbolic,
            ],
            math_tokens: MathSpecialTokens::default(),
            math_context_length: 8192,
            math_attention_patterns: true,
            model_variant: MathModelVariant::MathLlama,
            chain_of_thought: ChainOfThoughtConfig::default(),
        }
    }
}

impl MathSpecializedConfig {
    /// Math LLaMA 7B configuration
    pub fn math_llama_7b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 4096,
                intermediate_size: 11008,
                num_hidden_layers: 32,
                num_attention_heads: 32,
                max_position_embeddings: 8192,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(35000), // Extended vocabulary for math symbols
            math_context_length: 8192,
            model_variant: MathModelVariant::MathLlama,
            ..Self::default()
        }
    }

    /// Math LLaMA 13B configuration
    pub fn math_llama_13b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 5120,
                intermediate_size: 13824,
                num_hidden_layers: 40,
                num_attention_heads: 40,
                max_position_embeddings: 8192,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(35000),
            math_context_length: 8192,
            model_variant: MathModelVariant::MathLlama,
            ..Self::default()
        }
    }

    /// Math LLaMA 70B configuration
    pub fn math_llama_70b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 8192,
                intermediate_size: 28672,
                num_hidden_layers: 80,
                num_attention_heads: 64,
                num_key_value_heads: Some(8), // Grouped-query attention
                max_position_embeddings: 8192,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(35000),
            math_context_length: 8192,
            model_variant: MathModelVariant::MathLlama,
            ..Self::default()
        }
    }

    /// DeepSeek-Math 7B configuration
    pub fn deepseek_math_7b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 4096,
                intermediate_size: 11008,
                num_hidden_layers: 32,
                num_attention_heads: 32,
                max_position_embeddings: 16384,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(34000),
            math_context_length: 16384,
            model_variant: MathModelVariant::DeepSeekMath,
            supported_domains: vec![
                MathDomain::Elementary,
                MathDomain::Algebra,
                MathDomain::Calculus,
                MathDomain::LinearAlgebra,
                MathDomain::Logic,
                MathDomain::Competition,
            ],
            ..Self::default()
        }
    }

    /// DeepSeek-Math 67B configuration
    pub fn deepseek_math_67b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 8192,
                intermediate_size: 22016,
                num_hidden_layers: 95,
                num_attention_heads: 64,
                num_key_value_heads: Some(8),
                max_position_embeddings: 16384,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(34000),
            math_context_length: 16384,
            model_variant: MathModelVariant::DeepSeekMath,
            ..Self::default()
        }
    }

    /// Minerva 8B configuration (Google's mathematical reasoning model)
    pub fn minerva_8b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 4096,
                intermediate_size: 16384,
                num_hidden_layers: 32,
                num_attention_heads: 32,
                max_position_embeddings: 2048,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(33000),
            math_context_length: 2048,
            model_variant: MathModelVariant::Minerva,
            latex_support: true,
            formula_parsing: true,
            supported_domains: vec![
                MathDomain::Elementary,
                MathDomain::Algebra,
                MathDomain::Calculus,
                MathDomain::LinearAlgebra,
                MathDomain::Statistics,
                MathDomain::Physics,
                MathDomain::Competition,
            ],
            ..Self::default()
        }
    }

    /// Minerva 62B configuration
    pub fn minerva_62b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 8192,
                intermediate_size: 32768,
                num_hidden_layers: 64,
                num_attention_heads: 64,
                num_key_value_heads: Some(8),
                max_position_embeddings: 2048,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(33000),
            math_context_length: 2048,
            model_variant: MathModelVariant::Minerva,
            ..Self::default()
        }
    }

    /// MAmmoTH 7B configuration
    pub fn mammoth_7b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 4096,
                intermediate_size: 11008,
                num_hidden_layers: 32,
                num_attention_heads: 32,
                max_position_embeddings: 8192,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(36000), // Larger vocabulary for diverse domains
            math_context_length: 8192,
            model_variant: MathModelVariant::Mammoth,
            supported_domains: vec![
                MathDomain::Elementary,
                MathDomain::Algebra,
                MathDomain::Calculus,
                MathDomain::LinearAlgebra,
                MathDomain::DiscreteMath,
                MathDomain::Statistics,
                MathDomain::Geometry,
                MathDomain::NumberTheory,
                MathDomain::Applied,
                MathDomain::Physics,
                MathDomain::ComputerScience,
                MathDomain::Competition,
            ],
            reasoning_strategies: vec![
                ReasoningStrategy::StepByStep,
                ReasoningStrategy::ChainOfThought,
                ReasoningStrategy::BackwardReasoning,
                ReasoningStrategy::CaseAnalysis,
                ReasoningStrategy::Induction,
                ReasoningStrategy::ProofByContradiction,
                ReasoningStrategy::Constructive,
                ReasoningStrategy::Analogical,
                ReasoningStrategy::Symbolic,
            ],
            ..Self::default()
        }
    }

    /// MAmmoTH 13B configuration
    pub fn mammoth_13b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32000,
                hidden_size: 5120,
                intermediate_size: 13824,
                num_hidden_layers: 40,
                num_attention_heads: 40,
                max_position_embeddings: 8192,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(36000),
            math_context_length: 8192,
            model_variant: MathModelVariant::Mammoth,
            ..Self::mammoth_7b()
        }
    }

    /// Qwen-Math 7B configuration
    pub fn qwen_math_7b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 151936,
                hidden_size: 3584,
                intermediate_size: 18944,
                num_hidden_layers: 28,
                num_attention_heads: 28,
                num_key_value_heads: Some(4),
                max_position_embeddings: 32768,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(155000), // Extended for math symbols
            math_context_length: 32768,    // Long context for complex problems
            model_variant: MathModelVariant::QwenMath,
            ..Self::default()
        }
    }

    /// Qwen-Math 72B configuration
    pub fn qwen_math_72b() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 151936,
                hidden_size: 8192,
                intermediate_size: 24576,
                num_hidden_layers: 80,
                num_attention_heads: 64,
                num_key_value_heads: Some(8),
                max_position_embeddings: 32768,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(155000),
            math_context_length: 32768,
            model_variant: MathModelVariant::QwenMath,
            ..Self::default()
        }
    }

    /// CodeT5-Math configuration (for code-math hybrid reasoning)
    pub fn codet5_math() -> Self {
        Self {
            base_config: LlamaConfig {
                vocab_size: 32100,
                hidden_size: 768,
                intermediate_size: 3072,
                num_hidden_layers: 12,
                num_attention_heads: 12,
                max_position_embeddings: 1024,
                ..LlamaConfig::default()
            },
            math_vocab_size: Some(35000),
            math_context_length: 1024,
            model_variant: MathModelVariant::CodeT5Math,
            symbolic_computation: true,
            supported_domains: vec![
                MathDomain::ComputerScience,
                MathDomain::Applied,
                MathDomain::DiscreteMath,
                MathDomain::Statistics,
            ],
            ..Self::default()
        }
    }

    /// Create configuration from model name
    pub fn from_pretrained_name(name: &str) -> Option<Self> {
        match name {
            // Math LLaMA variants
            "math-llama-7b" | "mathllama-7b" => Some(Self::math_llama_7b()),
            "math-llama-13b" | "mathllama-13b" => Some(Self::math_llama_13b()),
            "math-llama-70b" | "mathllama-70b" => Some(Self::math_llama_70b()),

            // DeepSeek-Math variants
            "deepseek-math-7b" => Some(Self::deepseek_math_7b()),
            "deepseek-math-67b" => Some(Self::deepseek_math_67b()),

            // Minerva variants
            "minerva-8b" | "google/minerva-8b" => Some(Self::minerva_8b()),
            "minerva-62b" | "google/minerva-62b" => Some(Self::minerva_62b()),

            // MAmmoTH variants
            "mammoth-7b" | "mammoth-math-7b" => Some(Self::mammoth_7b()),
            "mammoth-13b" | "mammoth-math-13b" => Some(Self::mammoth_13b()),

            // Qwen-Math variants
            "qwen-math-7b" | "Qwen/Qwen2-Math-7B" => Some(Self::qwen_math_7b()),
            "qwen-math-72b" | "Qwen/Qwen2-Math-72B" => Some(Self::qwen_math_72b()),

            // CodeT5-Math
            "codet5-math" | "Salesforce/codet5-math" => Some(Self::codet5_math()),

            _ => None,
        }
    }

    /// Get all available model names
    pub fn available_models() -> Vec<&'static str> {
        vec![
            // Math LLaMA
            "math-llama-7b",
            "math-llama-13b",
            "math-llama-70b",
            // DeepSeek-Math
            "deepseek-math-7b",
            "deepseek-math-67b",
            // Minerva
            "minerva-8b",
            "minerva-62b",
            // MAmmoTH
            "mammoth-7b",
            "mammoth-13b",
            // Qwen-Math
            "qwen-math-7b",
            "qwen-math-72b",
            // CodeT5-Math
            "codet5-math",
        ]
    }

    /// Check if configuration is valid
    pub fn validate(&self) -> Result<()> {
        self.base_config.validate()?;

        if self.math_context_length == 0 {
            return Err(invalid_config(
                "config_field",
                "Math context length must be greater than 0".to_string(),
            ));
        }

        if self.supported_domains.is_empty() {
            return Err(invalid_config(
                "config_field",
                "At least one mathematical domain must be supported".to_string(),
            ));
        }

        if self.reasoning_strategies.is_empty() {
            return Err(invalid_config(
                "config_field",
                "At least one reasoning strategy must be supported".to_string(),
            ));
        }

        if self.chain_of_thought.enabled && self.chain_of_thought.max_steps == 0 {
            return Err(invalid_config(
                "config_field",
                "Chain-of-thought max steps must be greater than 0".to_string(),
            ));
        }

        Ok(())
    }

    /// Get the effective vocabulary size
    pub fn effective_vocab_size(&self) -> usize {
        self.math_vocab_size.unwrap_or(self.base_config.vocab_size)
    }

    /// Check if model supports a specific mathematical domain
    pub fn supports_domain(&self, domain: &MathDomain) -> bool {
        self.supported_domains.contains(domain)
    }

    /// Check if model supports a specific reasoning strategy
    pub fn supports_strategy(&self, strategy: &ReasoningStrategy) -> bool {
        self.reasoning_strategies.contains(strategy)
    }

    /// Check if model supports LaTeX
    pub fn supports_latex(&self) -> bool {
        self.latex_support
    }

    /// Check if model supports symbolic computation
    pub fn supports_symbolic_computation(&self) -> bool {
        self.symbolic_computation
    }

    /// Get model architecture name
    pub fn architecture(&self) -> &'static str {
        match self.model_variant {
            MathModelVariant::MathLlama => "MathLlama",
            MathModelVariant::DeepSeekMath => "DeepSeekMath",
            MathModelVariant::PalmMath => "PaLMMath",
            MathModelVariant::Mammoth => "MAmmoTH",
            MathModelVariant::Minerva => "Minerva",
            MathModelVariant::QwenMath => "QwenMath",
            MathModelVariant::CodeT5Math => "CodeT5Math",
        }
    }
}

/// Mathematics-specialized model implementation
pub struct MathSpecializedModel {
    base_model: LlamaModel,
    config: MathSpecializedConfig,
}

impl MathSpecializedModel {
    /// Create a new mathematics-specialized model
    pub fn new(config: MathSpecializedConfig) -> Result<Self> {
        config.validate()?;
        let base_model = LlamaModel::new(config.base_config.clone())?;

        Ok(Self { base_model, config })
    }

    /// Get the configuration
    pub fn config(&self) -> &MathSpecializedConfig {
        &self.config
    }

    /// Check if model supports a specific mathematical domain
    pub fn supports_domain(&self, domain: &MathDomain) -> bool {
        self.config.supports_domain(domain)
    }

    /// Check if model supports a specific reasoning strategy
    pub fn supports_strategy(&self, strategy: &ReasoningStrategy) -> bool {
        self.config.supports_strategy(strategy)
    }

    /// Get supported mathematical domains
    pub fn supported_domains(&self) -> &[MathDomain] {
        &self.config.supported_domains
    }

    /// Get supported reasoning strategies
    pub fn supported_strategies(&self) -> &[ReasoningStrategy] {
        &self.config.reasoning_strategies
    }

    /// Create model from pretrained name
    pub fn from_pretrained_name(name: &str) -> Result<Self> {
        let config = MathSpecializedConfig::from_pretrained_name(name)
            .ok_or_else(|| invalid_config("model_name", format!("Unknown math model: {}", name)))?;
        Self::new(config)
    }
}

impl Layer for MathSpecializedModel {
    type Input = Vec<u32>; // Token IDs
    type Output = Tensor;

    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
        self.base_model.forward(input)
    }
}

/// Mathematics-specialized model with language modeling head
pub struct MathSpecializedForCausalLM {
    model: MathSpecializedModel,
    lm_head: trustformers_core::layers::Linear,
}

impl MathSpecializedForCausalLM {
    /// Create a new mathematics-specialized model for causal language modeling
    pub fn new(config: MathSpecializedConfig) -> Result<Self> {
        let vocab_size = config.effective_vocab_size();
        let hidden_size = config.base_config.hidden_size;

        let model = MathSpecializedModel::new(config)?;
        let lm_head = trustformers_core::layers::Linear::new(hidden_size, vocab_size, false);

        Ok(Self { model, lm_head })
    }

    /// Get the configuration
    pub fn config(&self) -> &MathSpecializedConfig {
        self.model.config()
    }

    /// Create model from pretrained name
    pub fn from_pretrained_name(name: &str) -> Result<Self> {
        let config = MathSpecializedConfig::from_pretrained_name(name)
            .ok_or_else(|| invalid_config("model_name", format!("Unknown math model: {}", name)))?;
        Self::new(config)
    }

    /// Solve a mathematical problem step-by-step (placeholder implementation)
    pub fn solve_step_by_step(&mut self, _problem: &str) -> Result<String> {
        // This is a placeholder implementation
        // In a real implementation, this would:
        // 1. Parse the mathematical problem
        // 2. Apply appropriate reasoning strategies
        // 3. Generate step-by-step solution
        // 4. Verify each step
        // 5. Format the final solution

        Ok("Step-by-step solution would be generated here".to_string())
    }

    /// Generate mathematical proof (placeholder implementation)
    pub fn generate_proof(&mut self, _theorem: &str) -> Result<String> {
        // Placeholder for proof generation
        Ok("Mathematical proof would be generated here".to_string())
    }

    /// Evaluate mathematical expression (placeholder implementation)
    pub fn evaluate_expression(&mut self, _expression: &str) -> Result<String> {
        // Placeholder for expression evaluation
        Ok("Expression evaluation would be performed here".to_string())
    }
}

impl Layer for MathSpecializedForCausalLM {
    type Input = Vec<u32>; // Token IDs
    type Output = Tensor;

    fn forward(&self, input: Self::Input) -> Result<Self::Output> {
        let hidden_states = self.model.forward(input)?;
        self.lm_head.forward(hidden_states)
    }
}

/// Mathematical problem types for specialized handling
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MathProblemType {
    /// Algebraic equations and manipulations
    Algebraic,
    /// Calculus problems (derivatives, integrals)
    Calculus,
    /// Geometry problems
    Geometry,
    /// Probability and statistics
    Statistics,
    /// Number theory problems
    NumberTheory,
    /// Linear algebra problems
    LinearAlgebra,
    /// Optimization problems
    Optimization,
    /// Differential equations
    DifferentialEquations,
    /// Mathematical proofs
    Proof,
    /// Word problems
    WordProblem,
}

/// Mathematical reasoning output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MathReasoningOutput {
    /// The original problem
    pub problem: String,
    /// Problem type classification
    pub problem_type: MathProblemType,
    /// Step-by-step solution
    pub steps: Vec<ReasoningStep>,
    /// Final answer
    pub answer: String,
    /// Confidence score (0-1)
    pub confidence: f32,
    /// Reasoning strategy used
    pub strategy: ReasoningStrategy,
}

/// Individual reasoning step
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReasoningStep {
    /// Step number
    pub step_number: usize,
    /// Step description
    pub description: String,
    /// Mathematical expression or equation
    pub expression: Option<String>,
    /// Justification for this step
    pub justification: String,
    /// Confidence in this step
    pub confidence: f32,
}

// Convenience type aliases for common math models
pub type MathLlamaConfig = MathSpecializedConfig;
pub type MathLlamaModel = MathSpecializedModel;
pub type MathLlamaForCausalLM = MathSpecializedForCausalLM;

pub type DeepSeekMathConfig = MathSpecializedConfig;
pub type DeepSeekMathModel = MathSpecializedModel;
pub type DeepSeekMathForCausalLM = MathSpecializedForCausalLM;

pub type MinervaConfig = MathSpecializedConfig;
pub type MinervaModel = MathSpecializedModel;
pub type MinervaForCausalLM = MathSpecializedForCausalLM;

pub type MammothConfig = MathSpecializedConfig;
pub type MammothModel = MathSpecializedModel;
pub type MammothForCausalLM = MathSpecializedForCausalLM;

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

    #[test]
    fn test_math_specialized_config_creation() {
        let config = MathSpecializedConfig::math_llama_7b();
        assert_eq!(config.base_config.hidden_size, 4096);
        assert_eq!(config.math_context_length, 8192);
        assert_eq!(config.model_variant, MathModelVariant::MathLlama);
        assert!(config.step_by_step_reasoning);
        assert!(config.math_notation_support);
    }

    #[test]
    fn test_deepseek_math_config() {
        let config = MathSpecializedConfig::deepseek_math_7b();
        assert_eq!(config.base_config.hidden_size, 4096);
        assert_eq!(config.math_context_length, 16384);
        assert_eq!(config.model_variant, MathModelVariant::DeepSeekMath);
        assert!(config.supports_domain(&MathDomain::Competition));
    }

    #[test]
    fn test_minerva_config() {
        let config = MathSpecializedConfig::minerva_8b();
        assert_eq!(config.base_config.hidden_size, 4096);
        assert_eq!(config.model_variant, MathModelVariant::Minerva);
        assert!(config.latex_support);
        assert!(config.formula_parsing);
    }

    #[test]
    fn test_mammoth_config() {
        let config = MathSpecializedConfig::mammoth_7b();
        assert_eq!(config.model_variant, MathModelVariant::Mammoth);
        assert_eq!(config.supported_domains.len(), 12); // All domains
        assert_eq!(config.reasoning_strategies.len(), 9); // All strategies including ProofByContradiction
    }

    #[test]
    fn test_from_pretrained_name() {
        let config = MathSpecializedConfig::from_pretrained_name("math-llama-7b");
        assert!(config.is_some());
        let config = config.expect("operation failed");
        assert_eq!(config.model_variant, MathModelVariant::MathLlama);

        let config = MathSpecializedConfig::from_pretrained_name("minerva-8b");
        assert!(config.is_some());
        let config = config.expect("operation failed");
        assert_eq!(config.model_variant, MathModelVariant::Minerva);

        let config = MathSpecializedConfig::from_pretrained_name("unknown-model");
        assert!(config.is_none());
    }

    #[test]
    fn test_available_models() {
        let models = MathSpecializedConfig::available_models();
        assert!(models.contains(&"math-llama-7b"));
        assert!(models.contains(&"deepseek-math-7b"));
        assert!(models.contains(&"minerva-8b"));
        assert!(models.contains(&"mammoth-7b"));
        assert!(models.contains(&"qwen-math-7b"));
        assert!(models.len() >= 11); // Should have at least 11 models
    }

    #[test]
    fn test_domain_support() {
        let config = MathSpecializedConfig::default();
        assert!(config.supports_domain(&MathDomain::Algebra));
        assert!(config.supports_domain(&MathDomain::Calculus));
        assert!(!config.supports_domain(&MathDomain::Competition));

        let mammoth_config = MathSpecializedConfig::mammoth_7b();
        assert!(mammoth_config.supports_domain(&MathDomain::Competition));
        assert!(mammoth_config.supports_domain(&MathDomain::NumberTheory));
    }

    #[test]
    fn test_strategy_support() {
        let config = MathSpecializedConfig::default();
        assert!(config.supports_strategy(&ReasoningStrategy::StepByStep));
        assert!(config.supports_strategy(&ReasoningStrategy::ChainOfThought));
        assert!(!config.supports_strategy(&ReasoningStrategy::Induction));

        let mammoth_config = MathSpecializedConfig::mammoth_7b();
        assert!(mammoth_config.supports_strategy(&ReasoningStrategy::Induction));
        assert!(mammoth_config.supports_strategy(&ReasoningStrategy::ProofByContradiction));
    }

    #[test]
    fn test_config_validation() {
        let config = MathSpecializedConfig::default();
        assert!(config.validate().is_ok());

        let invalid_config = MathSpecializedConfig {
            math_context_length: 0,
            ..MathSpecializedConfig::default()
        };
        assert!(invalid_config.validate().is_err());

        let mut invalid_config = MathSpecializedConfig::default();
        invalid_config.supported_domains.clear();
        assert!(invalid_config.validate().is_err());

        let mut invalid_config = MathSpecializedConfig::default();
        invalid_config.reasoning_strategies.clear();
        assert!(invalid_config.validate().is_err());
    }

    #[test]
    fn test_chain_of_thought_config() {
        let config = ChainOfThoughtConfig::default();
        assert!(config.enabled);
        assert_eq!(config.max_steps, 20);
        assert!(config.step_verification);
        assert!(config.confidence_scoring);
        assert!(config.backtrack_on_error);
    }

    #[test]
    fn test_math_special_tokens() {
        let tokens = MathSpecialTokens::default();
        assert_eq!(tokens.step_separator, "<step>");
        assert_eq!(tokens.solution_start, "<solution>");
        assert_eq!(tokens.therefore, "");
        assert_eq!(tokens.because, "");
        assert_eq!(tokens.qed, "");
    }

    #[test]
    fn test_effective_vocab_size() {
        let config = MathSpecializedConfig::math_llama_7b();
        assert_eq!(config.effective_vocab_size(), 35000);

        let mut config = MathSpecializedConfig {
            math_vocab_size: None,
            ..MathSpecializedConfig::default()
        };
        config.base_config.vocab_size = 50000;
        assert_eq!(config.effective_vocab_size(), 50000);
    }

    #[test]
    fn test_architecture_names() {
        let config = MathSpecializedConfig::math_llama_7b();
        assert_eq!(config.architecture(), "MathLlama");

        let config = MathSpecializedConfig::minerva_8b();
        assert_eq!(config.architecture(), "Minerva");

        let config = MathSpecializedConfig::deepseek_math_7b();
        assert_eq!(config.architecture(), "DeepSeekMath");
    }

    #[test]
    fn test_model_creation() {
        let config = MathSpecializedConfig {
            base_config: LlamaConfig {
                vocab_size: 1000,
                hidden_size: 64,
                intermediate_size: 256,
                num_hidden_layers: 2,
                num_attention_heads: 4,
                max_position_embeddings: 512,
                ..LlamaConfig::default()
            },
            math_context_length: 512,
            ..MathSpecializedConfig::default()
        };

        let model = MathSpecializedModel::new(config.clone());
        assert!(model.is_ok());
        let model = model.expect("operation failed");
        assert!(model.supports_domain(&MathDomain::Algebra));
        assert!(model.supports_strategy(&ReasoningStrategy::StepByStep));

        let causal_lm = MathSpecializedForCausalLM::new(config);
        assert!(causal_lm.is_ok());
    }

    #[test]
    fn test_math_problem_types() {
        // Test that all math problem types are properly defined
        let problem_types = [
            MathProblemType::Algebraic,
            MathProblemType::Calculus,
            MathProblemType::Geometry,
            MathProblemType::Statistics,
            MathProblemType::NumberTheory,
            MathProblemType::LinearAlgebra,
            MathProblemType::Optimization,
            MathProblemType::DifferentialEquations,
            MathProblemType::Proof,
            MathProblemType::WordProblem,
        ];
        assert_eq!(problem_types.len(), 10);
    }

    #[test]
    fn test_reasoning_step() {
        let step = ReasoningStep {
            step_number: 1,
            description: "Expand the expression".to_string(),
            expression: Some("(x + 1)^2 = x^2 + 2x + 1".to_string()),
            justification: "Using the binomial theorem".to_string(),
            confidence: 0.95,
        };
        assert_eq!(step.step_number, 1);
        assert!(step.expression.is_some());
        assert_eq!(step.confidence, 0.95);
    }

    #[test]
    fn test_qwen_math_long_context() {
        let config = MathSpecializedConfig::qwen_math_7b();
        assert_eq!(config.math_context_length, 32768); // Long context
        assert_eq!(config.model_variant, MathModelVariant::QwenMath);
    }

    #[test]
    fn test_codet5_math_config() {
        let config = MathSpecializedConfig::codet5_math();
        assert_eq!(config.model_variant, MathModelVariant::CodeT5Math);
        assert!(config.symbolic_computation);
        assert!(config.supports_domain(&MathDomain::ComputerScience));
    }
}