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
//! Core traits defining the fundamental abstractions of TrustformeRS.
//!
//! This module contains the essential traits that form the foundation of the TrustformeRS
//! transformer library. These traits define the interfaces for models, layers, configuration,
//! tokenization, optimization, and parameter initialization.
//!
//! # Overview
//!
//! The traits in this module establish a consistent API across all transformer implementations:
//!
//! - [`Model`]: The main trait for transformer models with forward pass and loading capabilities
//! - [`Layer`]: Building blocks for neural network architectures
//! - [`Config`]: Configuration management for models and components
//! - [`WeightReader`]: Interface for loading pretrained model weights
//! - [`Tokenizer`]: Text tokenization and encoding/decoding
//! - [`Optimizer`]: Parameter optimization algorithms
//! - [`ParameterInit`]: Weight initialization strategies
//!
//! # Examples
//!
//! ```no_run
//! use trustformers_core::traits::{Model, Config};
//! use trustformers_core::tensor::Tensor;
//! use trustformers_core::errors::Result;
//! use std::io::Read;
//! use serde::{Deserialize, Serialize};
//!
//! // Example model configuration
//! #[derive(Debug, Deserialize, Serialize)]
//! struct MyConfig { hidden_size: usize }
//! impl Config for MyConfig {
//! fn architecture(&self) -> &'static str { "my_model" }
//! }
//!
//! // Example model implementation
//! struct MyModel {
//! config: MyConfig,
//! // ... model layers
//! }
//!
//! impl Model for MyModel {
//! type Config = MyConfig;
//! type Input = Tensor;
//! type Output = Tensor;
//!
//! fn forward(&self, input: Self::Input) -> Result<Self::Output> {
//! // Model forward pass implementation
//! Ok(input)
//! }
//!
//! fn load_pretrained(&mut self, _reader: &mut dyn Read) -> Result<()> {
//! // Load pretrained weights
//! Ok(())
//! }
//!
//! fn get_config(&self) -> &Self::Config {
//! &self.config
//! }
//!
//! fn num_parameters(&self) -> usize { 0 }
//! }
//! ```
use crateResult;
use crateTensor;
use ;
use Read;
/// The main trait for transformer models.
///
/// This trait defines the interface that all transformer models must implement,
/// providing a consistent API for forward passes, weight loading, and configuration access.
///
/// # Type Parameters
///
/// - `Config`: The configuration type for this model, must implement [`Config`]
/// - `Input`: The input type for the model's forward pass
/// - `Output`: The output type produced by the model
///
/// # Thread Safety
///
/// Models must be `Send + Sync` to support multi-threaded inference and training.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::{Model, Config};
/// use trustformers_core::tensor::Tensor;
/// use trustformers_core::errors::Result;
/// use std::io::Read;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct BertConfig {
/// hidden_size: usize,
/// num_attention_heads: usize,
/// // ... other config fields
/// }
///
/// impl Config for BertConfig {
/// fn architecture(&self) -> &'static str {
/// "bert"
/// }
/// }
///
/// struct BertModel {
/// config: BertConfig,
/// // ... model layers
/// }
///
/// impl Model for BertModel {
/// type Config = BertConfig;
/// type Input = Tensor;
/// type Output = Tensor;
///
/// fn forward(&self, input: Self::Input) -> Result<Self::Output> {
/// // BERT forward pass implementation
/// Ok(input)
/// }
///
/// fn load_pretrained(&mut self, _reader: &mut dyn Read) -> Result<()> {
/// // Load BERT weights from reader
/// Ok(())
/// }
///
/// fn get_config(&self) -> &Self::Config {
/// &self.config
/// }
///
/// fn num_parameters(&self) -> usize { 0 }
/// }
/// ```
/// A building block for neural network architectures.
///
/// The `Layer` trait represents a single computational unit in a neural network,
/// such as a linear transformation, attention mechanism, or normalization layer.
/// Layers can be composed together to build complete models.
///
/// # Type Parameters
///
/// - `Input`: The input type accepted by this layer
/// - `Output`: The output type produced by this layer
///
/// # Thread Safety
///
/// Layers must be `Send + Sync` to support parallel computation.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::Layer;
/// use trustformers_core::tensor::Tensor;
/// use trustformers_core::errors::Result;
///
/// struct LinearLayer {
/// weight: Tensor,
/// bias: Option<Tensor>,
/// }
///
/// impl Layer for LinearLayer {
/// type Input = Tensor;
/// type Output = Tensor;
///
/// fn forward(&self, input: Self::Input) -> Result<Self::Output> {
/// // Compute linear transformation: y = xW^T + b
/// let output = input.matmul(&self.weight.transpose(0, 1)?)?;
/// if let Some(bias) = &self.bias {
/// output.add(bias)
/// } else {
/// Ok(output)
/// }
/// }
/// }
/// ```
/// Configuration trait for models and components.
///
/// This trait provides a standardized interface for configuration objects
/// that can be serialized, deserialized, and validated. All model configurations
/// must implement this trait to ensure compatibility with the TrustformeRS ecosystem.
///
/// # Requirements
///
/// Implementing types must be serializable and deserializable using serde.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::Config;
/// use trustformers_core::errors::{Result, TrustformersError};
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Clone, Deserialize, Serialize)]
/// struct GPT2Config {
/// vocab_size: usize,
/// hidden_size: usize,
/// num_layers: usize,
/// num_heads: usize,
/// }
///
/// impl Config for GPT2Config {
/// fn validate(&self) -> Result<()> {
/// if self.hidden_size % self.num_heads != 0 {
/// return Err(TrustformersError::invalid_input(
/// "hidden_size must be divisible by num_heads".to_string(),
/// ));
/// }
/// Ok(())
/// }
///
/// fn architecture(&self) -> &'static str {
/// "gpt2"
/// }
/// }
/// ```
/// Interface for reading model weights from various sources.
///
/// `WeightReader` provides an abstraction over different weight storage formats,
/// allowing models to load pretrained parameters from files, network sources,
/// or other storage backends.
///
/// # Supported Formats
///
/// Implementations may support various formats including:
/// - SafeTensors (.safetensors)
/// - PyTorch checkpoints (.pt, .bin)
/// - NumPy arrays (.npz)
/// - Custom formats
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::WeightReader;
/// use trustformers_core::tensor::Tensor;
/// use trustformers_core::errors::Result;
///
/// struct SafeTensorsReader {
/// // ... implementation details
/// }
///
/// impl WeightReader for SafeTensorsReader {
/// fn read_tensor(&mut self, _name: &str) -> Result<Tensor> {
/// // Read tensor from SafeTensors file
/// Ok(Tensor::zeros(&[768, 768])?)
/// }
///
/// fn list_tensors(&self) -> Vec<String> {
/// vec![
/// "bert.embeddings.word_embeddings.weight".to_string(),
/// "bert.encoder.layer.0.attention.self.query.weight".to_string(),
/// // ... more tensor names
/// ]
/// }
/// }
/// ```
/// Text tokenization interface for transformer models.
///
/// The `Tokenizer` trait provides methods for converting between text and token IDs,
/// which is essential for preparing input data for transformer models. Implementations
/// may use various tokenization algorithms such as WordPiece, BPE, or SentencePiece.
///
/// # Thread Safety
///
/// Tokenizers must be `Send + Sync` to support concurrent tokenization.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::{Tokenizer, TokenizedInput};
/// use trustformers_core::errors::Result;
/// use std::collections::HashMap;
///
/// struct BertTokenizer {
/// vocab: HashMap<String, u32>,
/// // ... other fields
/// }
///
/// impl Tokenizer for BertTokenizer {
/// fn encode(&self, _text: &str) -> Result<TokenizedInput> {
/// // Tokenize text into subwords
/// let tokens: Vec<u32> = vec![101, 2023, 2003, 1037, 3231, 102]; // [CLS] this is a test [SEP]
/// Ok(TokenizedInput::new(tokens, vec![1; 6]))
/// }
///
/// fn encode_pair(&self, text: &str, text2: &str) -> Result<TokenizedInput> {
/// // Encode two texts for tasks like question answering
/// let tokens1 = self.encode(text)?;
/// let tokens2 = self.encode(text2)?;
/// // Combine tokens with separator
/// let len1 = tokens1.input_ids.len();
/// let len2 = tokens2.input_ids.len();
/// let mut combined_ids = tokens1.input_ids;
/// combined_ids.extend_from_slice(&tokens2.input_ids);
/// let combined_len = combined_ids.len();
/// Ok(TokenizedInput::with_token_type_ids(
/// combined_ids,
/// vec![1; combined_len],
/// Some(vec![0; len1].into_iter().chain(vec![1; len2]).collect()),
/// ))
/// }
///
/// fn decode(&self, _ids: &[u32]) -> Result<String> {
/// // Convert token IDs back to text
/// Ok("this is a test".to_string())
/// }
///
/// fn vocab_size(&self) -> usize {
/// 30522 // BERT base vocabulary size
/// }
///
/// fn get_vocab(&self) -> HashMap<String, u32> {
/// self.vocab.clone()
/// }
///
/// fn token_to_id(&self, token: &str) -> Option<u32> {
/// self.vocab.get(token).copied()
/// }
///
/// fn id_to_token(&self, id: u32) -> Option<String> {
/// self.vocab.iter().find(|(_, &v)| v == id).map(|(k, _)| k.clone())
/// }
/// }
/// ```
/// Represents tokenized input ready for model consumption.
///
/// `TokenizedInput` contains all the necessary components for feeding
/// text data into a transformer model after tokenization.
///
/// # Fields
///
/// * `input_ids` - The token IDs representing the input text
/// * `attention_mask` - Binary mask (0 or 1) indicating which tokens are real vs padding
/// * `token_type_ids` - Optional segment IDs for models that use them (e.g., BERT)
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::TokenizedInput;
///
/// let input = TokenizedInput::with_token_type_ids(
/// vec![101, 2023, 2003, 1037, 3231, 102], // [CLS] this is a test [SEP]
/// vec![1, 1, 1, 1, 1, 1], // All tokens are real (not padding)
/// Some(vec![0, 0, 0, 0, 0, 0]), // All tokens from first segment
/// );
/// ```
/// Parameter optimization algorithms for training neural networks.
///
/// The `Optimizer` trait defines the interface for gradient-based optimization
/// algorithms such as SGD, Adam, AdamW, etc. Optimizers update model parameters
/// based on computed gradients to minimize the loss function.
///
/// # Thread Safety
///
/// Optimizers must be `Send + Sync` to support distributed training.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::Optimizer;
/// use trustformers_core::tensor::Tensor;
/// use trustformers_core::errors::Result;
///
/// struct SGD {
/// learning_rate: f32,
/// momentum: f32,
/// velocity: std::collections::HashMap<String, Tensor>,
/// }
///
/// impl Optimizer for SGD {
/// fn update(&mut self, _parameter: &mut Tensor, _grad: &Tensor) -> Result<()> {
/// // SGD with momentum: v = momentum * v - lr * grad
/// // parameter += v
/// Ok(())
/// }
///
/// fn zero_grad(&mut self) {
/// // Clear accumulated gradients
/// }
///
/// fn step(&mut self) {
/// // Apply updates to all parameters
/// }
///
/// fn get_lr(&self) -> f32 {
/// self.learning_rate
/// }
///
/// fn set_lr(&mut self, lr: f32) {
/// self.learning_rate = lr;
/// }
/// }
/// ```
/// Weight initialization strategies for neural network parameters.
///
/// The `ParameterInit` trait provides various initialization methods that help
/// ensure proper gradient flow and training stability. Different initialization
/// strategies are optimal for different activation functions and architectures.
///
/// # Example
///
/// ```no_run
/// use trustformers_core::traits::ParameterInit;
///
/// // Example type implementing ParameterInit
/// struct WeightMatrix {
/// data: Vec<f32>,
/// shape: [usize; 2],
/// }
///
/// impl ParameterInit for WeightMatrix {
/// fn normal(&mut self, mean: f32, std: f32) {
/// // fill data with normal distribution values
/// }
/// fn uniform(&mut self, min: f32, max: f32) {
/// // fill data with uniform distribution values
/// }
/// fn xavier_uniform(&mut self) {
/// // Xavier/Glorot initialization
/// }
/// fn xavier_normal(&mut self) {}
/// fn kaiming_uniform(&mut self, _mode: &str, _nonlinearity: &str) {}
/// fn kaiming_normal(&mut self, _mode: &str, _nonlinearity: &str) {}
/// }
///
/// let mut weight = WeightMatrix { data: vec![0.0; 768 * 768], shape: [768, 768] };
///
/// // Initialize with Xavier/Glorot uniform for tanh activations
/// weight.xavier_uniform();
///
/// // Or use Kaiming/He initialization for ReLU activations
/// weight.kaiming_normal("fan_in", "relu");
/// ```