tensorlogic-scirs-backend 0.1.0

SciRS2-powered tensor execution backend for TensorLogic
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
//! Precision control for tensor computations.
//!
//! This module provides abstractions for controlling numerical precision
//! (f32, f64, mixed precision).

use std::fmt;

/// Numerical precision for tensor computations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Precision {
    /// 32-bit floating point (faster, less memory)
    F32,

    /// 64-bit floating point (more accurate)
    #[default]
    F64,

    /// Mixed precision: f16 for storage, f32 for computation
    Mixed16,

    /// Mixed precision: bf16 for storage, f32 for computation
    BFloat16,
}

impl Precision {
    /// Returns the size in bytes of this precision.
    pub fn size_bytes(&self) -> usize {
        match self {
            Precision::F32 => 4,
            Precision::F64 => 8,
            Precision::Mixed16 => 2,  // Storage size
            Precision::BFloat16 => 2, // Storage size
        }
    }

    /// Returns true if this is a mixed precision mode.
    pub fn is_mixed(&self) -> bool {
        matches!(self, Precision::Mixed16 | Precision::BFloat16)
    }

    /// Returns the computation precision (the precision used for actual operations).
    pub fn compute_precision(&self) -> ComputePrecision {
        match self {
            Precision::F32 | Precision::Mixed16 | Precision::BFloat16 => ComputePrecision::F32,
            Precision::F64 => ComputePrecision::F64,
        }
    }

    /// Returns a human-readable description.
    pub fn description(&self) -> &'static str {
        match self {
            Precision::F32 => "32-bit floating point",
            Precision::F64 => "64-bit floating point",
            Precision::Mixed16 => "Mixed precision (FP16 storage, FP32 compute)",
            Precision::BFloat16 => "Mixed precision (BF16 storage, FP32 compute)",
        }
    }

    /// Memory savings compared to F64.
    pub fn memory_savings(&self) -> f64 {
        1.0 - (self.size_bytes() as f64 / 8.0)
    }
}

impl fmt::Display for Precision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Precision::F32 => write!(f, "FP32"),
            Precision::F64 => write!(f, "FP64"),
            Precision::Mixed16 => write!(f, "Mixed-FP16"),
            Precision::BFloat16 => write!(f, "Mixed-BF16"),
        }
    }
}

/// Computation precision (the actual precision used for operations).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComputePrecision {
    /// 32-bit computation
    F32,

    /// 64-bit computation
    F64,
}

impl fmt::Display for ComputePrecision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ComputePrecision::F32 => write!(f, "FP32"),
            ComputePrecision::F64 => write!(f, "FP64"),
        }
    }
}

/// Precision configuration for an executor.
#[derive(Debug, Clone)]
pub struct PrecisionConfig {
    /// Default precision for tensors
    pub default_precision: Precision,

    /// Enable automatic mixed precision
    pub auto_mixed_precision: bool,

    /// Loss scaling for mixed precision training
    pub loss_scale: Option<f64>,

    /// Dynamic loss scaling (adjust based on gradients)
    pub dynamic_loss_scaling: bool,
}

impl Default for PrecisionConfig {
    fn default() -> Self {
        Self {
            default_precision: Precision::F64,
            auto_mixed_precision: false,
            loss_scale: None,
            dynamic_loss_scaling: false,
        }
    }
}

impl PrecisionConfig {
    /// Create a configuration for FP32 precision.
    pub fn f32() -> Self {
        Self {
            default_precision: Precision::F32,
            auto_mixed_precision: false,
            loss_scale: None,
            dynamic_loss_scaling: false,
        }
    }

    /// Create a configuration for FP64 precision.
    pub fn f64() -> Self {
        Self {
            default_precision: Precision::F64,
            auto_mixed_precision: false,
            loss_scale: None,
            dynamic_loss_scaling: false,
        }
    }

    /// Create a configuration for mixed precision training.
    pub fn mixed_precision() -> Self {
        Self {
            default_precision: Precision::Mixed16,
            auto_mixed_precision: true,
            loss_scale: Some(2048.0), // Common starting value
            dynamic_loss_scaling: true,
        }
    }

    /// Enable automatic mixed precision.
    pub fn with_auto_mixed_precision(mut self, enable: bool) -> Self {
        self.auto_mixed_precision = enable;
        self
    }

    /// Set the loss scale for mixed precision training.
    pub fn with_loss_scale(mut self, scale: f64) -> Self {
        self.loss_scale = Some(scale);
        self
    }

    /// Enable dynamic loss scaling.
    pub fn with_dynamic_loss_scaling(mut self, enable: bool) -> Self {
        self.dynamic_loss_scaling = enable;
        self
    }
}

/// Trait for scalar types that can be used in tensor computations.
///
/// This trait abstracts over f32 and f64 for generic tensor operations.
pub trait Scalar:
    Copy
    + Clone
    + PartialEq
    + PartialOrd
    + std::fmt::Debug
    + std::fmt::Display
    + std::ops::Add<Output = Self>
    + std::ops::Sub<Output = Self>
    + std::ops::Mul<Output = Self>
    + std::ops::Div<Output = Self>
    + std::ops::Neg<Output = Self>
    + 'static
{
    /// Zero value
    fn zero() -> Self;

    /// One value
    fn one() -> Self;

    /// Maximum value
    fn max_value() -> Self;

    /// Minimum value (most negative)
    fn min_value() -> Self;

    /// Positive infinity
    fn infinity() -> Self;

    /// Negative infinity
    fn neg_infinity() -> Self;

    /// Not a number
    fn nan() -> Self;

    /// Check if value is NaN
    fn is_nan(self) -> bool;

    /// Check if value is infinite
    fn is_infinite(self) -> bool;

    /// Check if value is finite
    fn is_finite(self) -> bool;

    /// Absolute value
    fn abs(self) -> Self;

    /// Square root
    fn sqrt(self) -> Self;

    /// Exponential
    fn exp(self) -> Self;

    /// Natural logarithm
    fn ln(self) -> Self;

    /// Maximum of two values
    fn max(self, other: Self) -> Self;

    /// Minimum of two values
    fn min(self, other: Self) -> Self;

    /// Convert from f64
    fn from_f64(value: f64) -> Self;

    /// Convert to f64
    fn to_f64(self) -> f64;

    /// The precision type
    fn precision() -> Precision;
}

impl Scalar for f32 {
    fn zero() -> Self {
        0.0
    }

    fn one() -> Self {
        1.0
    }

    fn max_value() -> Self {
        f32::MAX
    }

    fn min_value() -> Self {
        f32::MIN
    }

    fn infinity() -> Self {
        f32::INFINITY
    }

    fn neg_infinity() -> Self {
        f32::NEG_INFINITY
    }

    fn nan() -> Self {
        f32::NAN
    }

    fn is_nan(self) -> bool {
        f32::is_nan(self)
    }

    fn is_infinite(self) -> bool {
        f32::is_infinite(self)
    }

    fn is_finite(self) -> bool {
        f32::is_finite(self)
    }

    fn abs(self) -> Self {
        f32::abs(self)
    }

    fn sqrt(self) -> Self {
        f32::sqrt(self)
    }

    fn exp(self) -> Self {
        f32::exp(self)
    }

    fn ln(self) -> Self {
        f32::ln(self)
    }

    fn max(self, other: Self) -> Self {
        f32::max(self, other)
    }

    fn min(self, other: Self) -> Self {
        f32::min(self, other)
    }

    fn from_f64(value: f64) -> Self {
        value as f32
    }

    fn to_f64(self) -> f64 {
        self as f64
    }

    fn precision() -> Precision {
        Precision::F32
    }
}

impl Scalar for f64 {
    fn zero() -> Self {
        0.0
    }

    fn one() -> Self {
        1.0
    }

    fn max_value() -> Self {
        f64::MAX
    }

    fn min_value() -> Self {
        f64::MIN
    }

    fn infinity() -> Self {
        f64::INFINITY
    }

    fn neg_infinity() -> Self {
        f64::NEG_INFINITY
    }

    fn nan() -> Self {
        f64::NAN
    }

    fn is_nan(self) -> bool {
        f64::is_nan(self)
    }

    fn is_infinite(self) -> bool {
        f64::is_infinite(self)
    }

    fn is_finite(self) -> bool {
        f64::is_finite(self)
    }

    fn abs(self) -> Self {
        f64::abs(self)
    }

    fn sqrt(self) -> Self {
        f64::sqrt(self)
    }

    fn exp(self) -> Self {
        f64::exp(self)
    }

    fn ln(self) -> Self {
        f64::ln(self)
    }

    fn max(self, other: Self) -> Self {
        f64::max(self, other)
    }

    fn min(self, other: Self) -> Self {
        f64::min(self, other)
    }

    fn from_f64(value: f64) -> Self {
        value
    }

    fn to_f64(self) -> f64 {
        self
    }

    fn precision() -> Precision {
        Precision::F64
    }
}

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

    #[test]
    fn test_precision_properties() {
        assert_eq!(Precision::F32.size_bytes(), 4);
        assert_eq!(Precision::F64.size_bytes(), 8);
        assert_eq!(Precision::Mixed16.size_bytes(), 2);

        assert!(!Precision::F32.is_mixed());
        assert!(!Precision::F64.is_mixed());
        assert!(Precision::Mixed16.is_mixed());
    }

    #[test]
    fn test_precision_default() {
        let precision = Precision::default();
        assert_eq!(precision, Precision::F64);
    }

    #[test]
    fn test_precision_display() {
        assert_eq!(Precision::F32.to_string(), "FP32");
        assert_eq!(Precision::F64.to_string(), "FP64");
        assert_eq!(Precision::Mixed16.to_string(), "Mixed-FP16");
    }

    #[test]
    fn test_precision_memory_savings() {
        assert!((Precision::F32.memory_savings() - 0.5).abs() < 0.01); // 50% savings vs F64
        assert!((Precision::F64.memory_savings()).abs() < 0.01); // 0% savings
        assert!((Precision::Mixed16.memory_savings() - 0.75).abs() < 0.01); // 75% savings
    }

    #[test]
    fn test_precision_config_default() {
        let config = PrecisionConfig::default();
        assert_eq!(config.default_precision, Precision::F64);
        assert!(!config.auto_mixed_precision);
    }

    #[test]
    fn test_precision_config_builders() {
        let f32_config = PrecisionConfig::f32();
        assert_eq!(f32_config.default_precision, Precision::F32);

        let f64_config = PrecisionConfig::f64();
        assert_eq!(f64_config.default_precision, Precision::F64);

        let mixed_config = PrecisionConfig::mixed_precision();
        assert_eq!(mixed_config.default_precision, Precision::Mixed16);
        assert!(mixed_config.auto_mixed_precision);
        assert!(mixed_config.loss_scale.is_some());
    }

    #[test]
    fn test_precision_config_builder_methods() {
        let config = PrecisionConfig::f32()
            .with_auto_mixed_precision(true)
            .with_loss_scale(1024.0)
            .with_dynamic_loss_scaling(true);

        assert!(config.auto_mixed_precision);
        assert_eq!(config.loss_scale, Some(1024.0));
        assert!(config.dynamic_loss_scaling);
    }

    #[test]
    fn test_scalar_f32() {
        assert_eq!(f32::zero(), 0.0_f32);
        assert_eq!(f32::one(), 1.0_f32);
        assert!(f32::infinity().is_infinite());
        assert!(f32::nan().is_nan());

        let x = 2.0_f32;
        assert_eq!(x.abs(), 2.0);
        assert!((x.sqrt() - std::f32::consts::SQRT_2).abs() < 1e-6);
        assert_eq!(f32::precision(), Precision::F32);
    }

    #[test]
    fn test_scalar_f64() {
        assert_eq!(f64::zero(), 0.0_f64);
        assert_eq!(f64::one(), 1.0_f64);
        assert!(f64::infinity().is_infinite());
        assert!(f64::nan().is_nan());

        let x = 2.0_f64;
        assert_eq!(x.abs(), 2.0);
        assert!((x.sqrt() - std::f64::consts::SQRT_2).abs() < 1e-10);
        assert_eq!(f64::precision(), Precision::F64);
    }

    #[test]
    fn test_scalar_conversions() {
        let x_f64 = std::f64::consts::PI;
        let x_f32 = f32::from_f64(x_f64);
        let back_to_f64 = x_f32.to_f64();

        assert!((x_f32 - std::f32::consts::PI).abs() < 1e-5);
        assert!((back_to_f64 - x_f64).abs() < 1e-5);
    }
}