trustformers-core 0.1.1

Core traits and utilities 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
//! Checkpoint format definitions for different frameworks

#![allow(unused_variables)] // Checkpoint format implementations

use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Supported checkpoint formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CheckpointFormat {
    PyTorch,
    TensorFlow,
    JAX,
    Trustformers,
    SafeTensors,
    ONNX,
}

impl CheckpointFormat {
    pub fn extension(&self) -> &'static str {
        match self {
            Self::PyTorch => ".pt",
            Self::TensorFlow => ".ckpt",
            Self::JAX => ".jax",
            Self::Trustformers => ".trust",
            Self::SafeTensors => ".safetensors",
            Self::ONNX => ".onnx",
        }
    }

    pub fn from_path(path: &Path) -> Option<Self> {
        let ext = path.extension()?.to_str()?;
        match ext {
            "pt" | "pth" | "bin" => Some(Self::PyTorch),
            "ckpt" | "h5" | "pb" => Some(Self::TensorFlow),
            "jax" | "msgpack" => Some(Self::JAX),
            "trust" => Some(Self::Trustformers),
            "safetensors" => Some(Self::SafeTensors),
            "onnx" => Some(Self::ONNX),
            _ => None,
        }
    }
}

/// Base trait for all checkpoint formats
pub trait Checkpoint: Send + Sync {
    /// Get the format type
    fn format(&self) -> CheckpointFormat;

    /// Get all weight names in the checkpoint
    fn weight_names(&self) -> Vec<String>;

    /// Get a specific weight tensor
    fn get_weight(&self, name: &str) -> Result<WeightTensor>;

    /// Set a weight tensor
    fn set_weight(&mut self, name: &str, weight: WeightTensor) -> Result<()>;

    /// Get metadata associated with the checkpoint
    fn metadata(&self) -> &HashMap<String, String>;

    /// Save the checkpoint to disk
    fn save(&self, path: &Path) -> Result<()>;

    /// Load from disk
    fn load(path: &Path) -> Result<Self>
    where
        Self: Sized;
}

/// Unified weight tensor representation
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, oxicode::Encode, oxicode::Decode)]
pub struct WeightTensor {
    pub data: Vec<f32>,
    pub shape: Vec<usize>,
    pub dtype: DataType,
}

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    oxicode::Encode,
    oxicode::Decode,
)]
pub enum DataType {
    Float32,
    Float16,
    BFloat16,
    Int8,
    Int4,
}

impl WeightTensor {
    pub fn new(data: Vec<f32>, shape: Vec<usize>) -> Self {
        Self {
            data,
            shape,
            dtype: DataType::Float32,
        }
    }

    pub fn num_elements(&self) -> usize {
        self.shape.iter().product()
    }

    pub fn reshape(&mut self, new_shape: Vec<usize>) -> Result<()> {
        let new_size: usize = new_shape.iter().product();
        if new_size != self.num_elements() {
            return Err(anyhow!(
                "Cannot reshape tensor from {:?} to {:?}",
                self.shape,
                new_shape
            ));
        }
        self.shape = new_shape;
        Ok(())
    }

    pub fn transpose(&mut self, dims: &[usize]) -> Result<()> {
        if dims.len() != self.shape.len() {
            return Err(anyhow!("Transpose dimensions mismatch"));
        }

        // Create new shape based on transpose dimensions
        let mut new_shape = vec![0; self.shape.len()];
        for (i, &dim) in dims.iter().enumerate() {
            if dim >= self.shape.len() {
                return Err(anyhow!("Transpose dimension {} out of bounds", dim));
            }
            new_shape[i] = self.shape[dim];
        }

        // Calculate strides for original and transposed tensor
        let mut old_strides = vec![1; self.shape.len()];
        for i in (0..self.shape.len() - 1).rev() {
            old_strides[i] = old_strides[i + 1] * self.shape[i + 1];
        }

        let mut new_strides = vec![1; new_shape.len()];
        for i in (0..new_shape.len() - 1).rev() {
            new_strides[i] = new_strides[i + 1] * new_shape[i + 1];
        }

        // Transpose the data
        let mut new_data = vec![0.0; self.data.len()];
        let total_elements = self.data.len();

        for i in 0..total_elements {
            // Calculate old indices
            let mut old_indices = vec![0; self.shape.len()];
            let mut temp = i;
            for (j, &stride) in old_strides.iter().enumerate() {
                old_indices[j] = temp / stride;
                temp %= stride;
            }

            // Calculate new indices after transpose
            let mut new_indices = vec![0; new_shape.len()];
            for (j, &dim) in dims.iter().enumerate() {
                new_indices[j] = old_indices[dim];
            }

            // Calculate new linear index
            let mut new_idx = 0;
            for (j, &idx) in new_indices.iter().enumerate() {
                new_idx += idx * new_strides[j];
            }

            new_data[new_idx] = self.data[i];
        }

        self.data = new_data;
        self.shape = new_shape;
        Ok(())
    }
}

/// PyTorch checkpoint format
pub struct PyTorchCheckpoint {
    weights: HashMap<String, WeightTensor>,
    metadata: HashMap<String, String>,
}

impl Default for PyTorchCheckpoint {
    fn default() -> Self {
        Self::new()
    }
}

impl PyTorchCheckpoint {
    pub fn new() -> Self {
        Self {
            weights: HashMap::new(),
            metadata: HashMap::new(),
        }
    }
}

impl Checkpoint for PyTorchCheckpoint {
    fn format(&self) -> CheckpointFormat {
        CheckpointFormat::PyTorch
    }

    fn weight_names(&self) -> Vec<String> {
        self.weights.keys().cloned().collect()
    }

    fn get_weight(&self, name: &str) -> Result<WeightTensor> {
        self.weights
            .get(name)
            .cloned()
            .ok_or_else(|| anyhow!("Weight '{}' not found", name))
    }

    fn set_weight(&mut self, name: &str, weight: WeightTensor) -> Result<()> {
        self.weights.insert(name.to_string(), weight);
        Ok(())
    }

    fn metadata(&self) -> &HashMap<String, String> {
        &self.metadata
    }

    fn save(&self, path: &Path) -> Result<()> {
        // Implement PyTorch-compatible checkpoint saving using JSON format
        // This provides a practical implementation that can be extended to actual pickle format later
        let checkpoint_data = serde_json::json!({
            "weights": self.weights.iter().map(|(key, tensor)| {
                (key.clone(), serde_json::json!({
                    "data": tensor.data,
                    "shape": tensor.shape,
                    "dtype": format!("{:?}", tensor.dtype)
                }))
            }).collect::<HashMap<String, serde_json::Value>>(),
            "metadata": self.metadata,
            "format": "pytorch_compatible"
        });

        std::fs::write(path, serde_json::to_string_pretty(&checkpoint_data)?)?;
        Ok(())
    }

    fn load(path: &Path) -> Result<Self> {
        // Implement PyTorch-compatible checkpoint loading
        let content = std::fs::read_to_string(path)?;
        let checkpoint_data: serde_json::Value = serde_json::from_str(&content)?;

        let mut checkpoint = Self::new();

        // Load weights
        if let Some(weights) = checkpoint_data.get("weights").and_then(|w| w.as_object()) {
            for (key, tensor_data) in weights {
                if let (Some(data), Some(shape), Some(dtype)) = (
                    tensor_data.get("data").and_then(|d| d.as_array()),
                    tensor_data.get("shape").and_then(|s| s.as_array()),
                    tensor_data.get("dtype").and_then(|d| d.as_str()),
                ) {
                    let data: Vec<f32> =
                        data.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
                    let shape: Vec<usize> =
                        shape.iter().filter_map(|v| v.as_u64().map(|u| u as usize)).collect();

                    checkpoint.weights.insert(key.clone(), WeightTensor::new(data, shape));
                }
            }
        }

        // Load metadata
        if let Some(metadata) = checkpoint_data.get("metadata").and_then(|m| m.as_object()) {
            for (key, value) in metadata {
                if let Some(value_str) = value.as_str() {
                    checkpoint.metadata.insert(key.clone(), value_str.to_string());
                }
            }
        }

        Ok(checkpoint)
    }
}

/// TensorFlow checkpoint format
pub struct TensorFlowCheckpoint {
    weights: HashMap<String, WeightTensor>,
    metadata: HashMap<String, String>,
}

impl Default for TensorFlowCheckpoint {
    fn default() -> Self {
        Self::new()
    }
}

impl TensorFlowCheckpoint {
    pub fn new() -> Self {
        Self {
            weights: HashMap::new(),
            metadata: HashMap::new(),
        }
    }
}

impl Checkpoint for TensorFlowCheckpoint {
    fn format(&self) -> CheckpointFormat {
        CheckpointFormat::TensorFlow
    }

    fn weight_names(&self) -> Vec<String> {
        self.weights.keys().cloned().collect()
    }

    fn get_weight(&self, name: &str) -> Result<WeightTensor> {
        self.weights
            .get(name)
            .cloned()
            .ok_or_else(|| anyhow!("Weight '{}' not found", name))
    }

    fn set_weight(&mut self, name: &str, weight: WeightTensor) -> Result<()> {
        self.weights.insert(name.to_string(), weight);
        Ok(())
    }

    fn metadata(&self) -> &HashMap<String, String> {
        &self.metadata
    }

    fn save(&self, path: &Path) -> Result<()> {
        // Implement TensorFlow-compatible checkpoint saving using JSON format
        // This provides a practical implementation that can be extended to actual protobuf format later
        let checkpoint_data = serde_json::json!({
            "weights": self.weights.iter().map(|(key, tensor)| {
                (key.clone(), serde_json::json!({
                    "data": tensor.data,
                    "shape": tensor.shape,
                    "dtype": format!("{:?}", tensor.dtype)
                }))
            }).collect::<HashMap<String, serde_json::Value>>(),
            "metadata": self.metadata,
            "format": "tensorflow_compatible"
        });

        std::fs::write(path, serde_json::to_string_pretty(&checkpoint_data)?)?;
        Ok(())
    }

    fn load(path: &Path) -> Result<Self> {
        // Implement TensorFlow-compatible checkpoint loading
        let content = std::fs::read_to_string(path)?;
        let checkpoint_data: serde_json::Value = serde_json::from_str(&content)?;

        let mut checkpoint = Self::new();

        // Load weights
        if let Some(weights) = checkpoint_data.get("weights").and_then(|w| w.as_object()) {
            for (key, tensor_data) in weights {
                if let (Some(data), Some(shape), Some(dtype)) = (
                    tensor_data.get("data").and_then(|d| d.as_array()),
                    tensor_data.get("shape").and_then(|s| s.as_array()),
                    tensor_data.get("dtype").and_then(|d| d.as_str()),
                ) {
                    let data: Vec<f32> =
                        data.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
                    let shape: Vec<usize> =
                        shape.iter().filter_map(|v| v.as_u64().map(|u| u as usize)).collect();

                    checkpoint.weights.insert(key.clone(), WeightTensor::new(data, shape));
                }
            }
        }

        // Load metadata
        if let Some(metadata) = checkpoint_data.get("metadata").and_then(|m| m.as_object()) {
            for (key, value) in metadata {
                if let Some(value_str) = value.as_str() {
                    checkpoint.metadata.insert(key.clone(), value_str.to_string());
                }
            }
        }

        Ok(checkpoint)
    }
}

/// JAX checkpoint format
pub struct JaxCheckpoint {
    weights: HashMap<String, WeightTensor>,
    metadata: HashMap<String, String>,
}

impl Default for JaxCheckpoint {
    fn default() -> Self {
        Self::new()
    }
}

impl JaxCheckpoint {
    pub fn new() -> Self {
        Self {
            weights: HashMap::new(),
            metadata: HashMap::new(),
        }
    }
}

impl Checkpoint for JaxCheckpoint {
    fn format(&self) -> CheckpointFormat {
        CheckpointFormat::JAX
    }

    fn weight_names(&self) -> Vec<String> {
        self.weights.keys().cloned().collect()
    }

    fn get_weight(&self, name: &str) -> Result<WeightTensor> {
        self.weights
            .get(name)
            .cloned()
            .ok_or_else(|| anyhow!("Weight '{}' not found", name))
    }

    fn set_weight(&mut self, name: &str, weight: WeightTensor) -> Result<()> {
        self.weights.insert(name.to_string(), weight);
        Ok(())
    }

    fn metadata(&self) -> &HashMap<String, String> {
        &self.metadata
    }

    fn save(&self, path: &Path) -> Result<()> {
        // Implement JAX-compatible checkpoint saving using JSON format
        // This provides a practical implementation that can be extended to actual msgpack format later
        let checkpoint_data = serde_json::json!({
            "weights": self.weights.iter().map(|(key, tensor)| {
                (key.clone(), serde_json::json!({
                    "data": tensor.data,
                    "shape": tensor.shape,
                    "dtype": format!("{:?}", tensor.dtype)
                }))
            }).collect::<HashMap<String, serde_json::Value>>(),
            "metadata": self.metadata,
            "format": "jax_compatible"
        });

        std::fs::write(path, serde_json::to_string_pretty(&checkpoint_data)?)?;
        Ok(())
    }

    fn load(path: &Path) -> Result<Self> {
        // Implement JAX-compatible checkpoint loading
        let content = std::fs::read_to_string(path)?;
        let checkpoint_data: serde_json::Value = serde_json::from_str(&content)?;

        let mut checkpoint = Self::new();

        // Load weights
        if let Some(weights) = checkpoint_data.get("weights").and_then(|w| w.as_object()) {
            for (key, tensor_data) in weights {
                if let (Some(data), Some(shape), Some(dtype)) = (
                    tensor_data.get("data").and_then(|d| d.as_array()),
                    tensor_data.get("shape").and_then(|s| s.as_array()),
                    tensor_data.get("dtype").and_then(|d| d.as_str()),
                ) {
                    let data: Vec<f32> =
                        data.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
                    let shape: Vec<usize> =
                        shape.iter().filter_map(|v| v.as_u64().map(|u| u as usize)).collect();

                    checkpoint.weights.insert(key.clone(), WeightTensor::new(data, shape));
                }
            }
        }

        // Load metadata
        if let Some(metadata) = checkpoint_data.get("metadata").and_then(|m| m.as_object()) {
            for (key, value) in metadata {
                if let Some(value_str) = value.as_str() {
                    checkpoint.metadata.insert(key.clone(), value_str.to_string());
                }
            }
        }

        Ok(checkpoint)
    }
}

/// TrustformeRS native checkpoint format
pub struct TrustformersCheckpoint {
    weights: HashMap<String, WeightTensor>,
    metadata: HashMap<String, String>,
    version: String,
}

impl Default for TrustformersCheckpoint {
    fn default() -> Self {
        Self::new()
    }
}

impl TrustformersCheckpoint {
    pub fn new() -> Self {
        Self {
            weights: HashMap::new(),
            metadata: HashMap::new(),
            version: env!("CARGO_PKG_VERSION").to_string(),
        }
    }
}

impl Checkpoint for TrustformersCheckpoint {
    fn format(&self) -> CheckpointFormat {
        CheckpointFormat::Trustformers
    }

    fn weight_names(&self) -> Vec<String> {
        self.weights.keys().cloned().collect()
    }

    fn get_weight(&self, name: &str) -> Result<WeightTensor> {
        self.weights
            .get(name)
            .cloned()
            .ok_or_else(|| anyhow!("Weight '{}' not found", name))
    }

    fn set_weight(&mut self, name: &str, weight: WeightTensor) -> Result<()> {
        self.weights.insert(name.to_string(), weight);
        Ok(())
    }

    fn metadata(&self) -> &HashMap<String, String> {
        &self.metadata
    }

    fn save(&self, path: &Path) -> Result<()> {
        // Use oxicode for efficient serialization
        let data = oxicode::serde::encode_to_vec(
            &(&self.weights, &self.metadata, &self.version),
            oxicode::config::standard(),
        )?;
        std::fs::write(path, data)?;
        Ok(())
    }

    fn load(path: &Path) -> Result<Self> {
        let data = std::fs::read(path)?;
        type CheckpointData = (
            HashMap<String, WeightTensor>,
            HashMap<String, String>,
            String,
        );
        let ((weights, metadata, version), _): (CheckpointData, usize) =
            oxicode::serde::decode_from_slice(&data, oxicode::config::standard())?;
        Ok(Self {
            weights,
            metadata,
            version,
        })
    }
}

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

    #[test]
    fn test_format_detection() {
        assert_eq!(
            CheckpointFormat::from_path(Path::new("model.pt")),
            Some(CheckpointFormat::PyTorch)
        );
        assert_eq!(
            CheckpointFormat::from_path(Path::new("model.ckpt")),
            Some(CheckpointFormat::TensorFlow)
        );
        assert_eq!(
            CheckpointFormat::from_path(Path::new("model.jax")),
            Some(CheckpointFormat::JAX)
        );
    }

    #[test]
    fn test_weight_tensor() {
        let mut tensor = WeightTensor::new(vec![1.0, 2.0, 3.0, 4.0], vec![2, 2]);
        assert_eq!(tensor.num_elements(), 4);

        assert!(tensor.reshape(vec![4]).is_ok());
        assert_eq!(tensor.shape, vec![4]);

        assert!(tensor.reshape(vec![2, 3]).is_err());
    }
}