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
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Unified Math Base - Hardware-Agnostic Mathematical Primitives
//!
//! **Philosophy**: Define WHAT to compute, not HOW
//!
//! This module provides the mathematical foundation for `BarraCuda`:
//! - Pure mathematical definitions (no hardware assumptions)
//! - Trait-based abstraction (works with any backend)
//! - Composable primitives (build complex ops from simple ones)
//! - Type-safe tensors (compile-time shape checking where possible)
//!
//! **Deep Debt Principles**:
//! - ✅ Hardware agnostic (no GPU/CPU/TPU assumptions)
//! - ✅ Math-first (correct semantics before optimization)
//! - ✅ Composable (primitives combine naturally)
//! - ✅ Type-safe (catch errors at compile time)
use std::fmt;
/// Mathematical operation primitive
///
/// Represents a fundamental mathematical operation that can be
/// executed on any hardware backend (GPU, CPU, TPU, NPU).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MathOp {
// ═══════════════════════════════════════════════════════════
// UNARY OPERATIONS (one input, one output)
// ═══════════════════════════════════════════════════════════
/// Negate: y = -x
Negate,
/// Absolute value: y = |x|
Abs,
/// Square: y = x²
Square,
/// Square root: y = √x
Sqrt,
/// Reciprocal: y = 1/x
Reciprocal,
/// Exponential: y = eˣ
Exp,
/// Natural log: y = ln(x)
Log,
/// Sine: y = sin(x)
Sin,
/// Cosine: y = cos(x)
Cos,
/// Tangent: y = tan(x)
Tan,
// ═══════════════════════════════════════════════════════════
// BINARY OPERATIONS (two inputs, one output)
// ═══════════════════════════════════════════════════════════
/// Addition: z = x + y
Add,
/// Subtraction: z = x - y
Sub,
/// Multiplication: z = x * y
Mul,
/// Division: z = x / y
Div,
/// Power: z = xʸ
Pow,
/// Maximum: z = max(x, y)
Max,
/// Minimum: z = min(x, y)
Min,
// ═══════════════════════════════════════════════════════════
// REDUCTION OPERATIONS (reduce along dimension)
// ═══════════════════════════════════════════════════════════
/// Sum reduction: ∑x
ReduceSum {
/// Dimension along which to reduce; `None` reduces all.
dim: Option<usize>,
/// Whether to keep the reduced dimension with size 1.
keepdim: bool,
},
/// Mean reduction: mean(x)
ReduceMean {
/// Dimension along which to reduce; `None` reduces all.
dim: Option<usize>,
/// Whether to keep the reduced dimension with size 1.
keepdim: bool,
},
/// Max reduction: max(x)
ReduceMax {
/// Dimension along which to reduce; `None` reduces all.
dim: Option<usize>,
/// Whether to keep the reduced dimension with size 1.
keepdim: bool,
},
/// Min reduction: min(x)
ReduceMin {
/// Dimension along which to reduce; `None` reduces all.
dim: Option<usize>,
/// Whether to keep the reduced dimension with size 1.
keepdim: bool,
},
/// Product reduction: ∏x
ReduceProd {
/// Dimension along which to reduce; `None` reduces all.
dim: Option<usize>,
/// Whether to keep the reduced dimension with size 1.
keepdim: bool,
},
// ═══════════════════════════════════════════════════════════
// MATRIX OPERATIONS
// ═══════════════════════════════════════════════════════════
/// Matrix multiply: C = A @ B
MatMul {
/// Whether to transpose the first matrix.
transpose_a: bool,
/// Whether to transpose the second matrix.
transpose_b: bool,
},
/// Matrix transpose: Aᵀ
Transpose {
/// Permutation of dimension indices.
perm: Vec<usize>,
},
/// Batch matrix multiply: [C₁, C₂, ...] = [A₁, A₂, ...] @ [B₁, B₂, ...]
BatchMatMul {
/// Whether to transpose the first matrix in each batch.
transpose_a: bool,
/// Whether to transpose the second matrix in each batch.
transpose_b: bool,
},
// ═══════════════════════════════════════════════════════════
// SHAPE OPERATIONS
// ═══════════════════════════════════════════════════════════
/// Reshape: change shape without copying data
Reshape {
/// Target shape dimensions (-1 for inferred).
new_shape: Vec<i64>,
},
/// Broadcast: expand shape by repeating values
Broadcast {
/// Target shape to broadcast to.
target_shape: Vec<usize>,
},
/// Squeeze: remove dimensions of size 1
Squeeze {
/// Dimensions to squeeze; `None` squeezes all size-1 dims.
dims: Option<Vec<usize>>,
},
/// Unsqueeze: add dimensions of size 1
Unsqueeze {
/// Dimensions at which to insert size-1.
dims: Vec<usize>,
},
/// Concat: join tensors along dimension
Concat {
/// Dimension along which to concatenate.
dim: usize,
},
/// Split: split tensor along dimension
Split {
/// Dimension along which to split.
dim: usize,
/// Size of each split chunk.
sizes: Vec<usize>,
},
// ═══════════════════════════════════════════════════════════
// ACTIVATION FUNCTIONS
// ═══════════════════════════════════════════════════════════
/// `ReLU`: max(0, x)
ReLU,
/// Sigmoid: 1 / (1 + e⁻ˣ)
Sigmoid,
/// Tanh: (eˣ - e⁻ˣ) / (eˣ + e⁻ˣ)
Tanh,
/// Softmax: eˣⁱ / ∑eˣʲ
Softmax {
/// Dimension along which to apply softmax.
dim: i64,
},
/// GELU: x * Φ(x) where Φ is standard normal CDF
GELU,
// ═══════════════════════════════════════════════════════════
// CONVOLUTION OPERATIONS
// ═══════════════════════════════════════════════════════════
/// 2D Convolution
Conv2D {
/// Stride (height, width).
stride: (usize, usize),
/// Padding (height, width).
padding: (usize, usize),
/// Dilation (height, width).
dilation: (usize, usize),
/// Number of groups for grouped convolution.
groups: usize,
},
/// 2D Max Pooling
MaxPool2D {
/// Kernel size (height, width).
kernel_size: (usize, usize),
/// Stride (height, width).
stride: (usize, usize),
/// Padding (height, width).
padding: (usize, usize),
},
/// 2D Average Pooling
AvgPool2D {
/// Kernel size (height, width).
kernel_size: (usize, usize),
/// Stride (height, width).
stride: (usize, usize),
/// Padding (height, width).
padding: (usize, usize),
},
}
/// Unified math primitive trait
///
/// **Hardware-agnostic**: Define math operations without knowing the backend
pub trait MathPrimitive {
/// Data type (f32, f64, i32, etc.)
type Scalar: Copy + fmt::Debug;
/// Execute unary operation: y = op(x)
fn unary(&self, op: UnaryOp, x: &[Self::Scalar]) -> Vec<Self::Scalar>;
/// Execute binary operation: z = op(x, y)
fn binary(&self, op: BinaryOp, x: &[Self::Scalar], y: &[Self::Scalar]) -> Vec<Self::Scalar>;
/// Execute reduction: y = reduce(x, dim)
fn reduce(
&self,
op: ReduceOp,
x: &[Self::Scalar],
shape: &[usize],
dim: Option<usize>,
) -> Vec<Self::Scalar>;
/// Execute matrix multiply: C = A @ B
fn matmul(
&self,
a: &[Self::Scalar],
b: &[Self::Scalar],
m: usize,
n: usize,
k: usize,
) -> Vec<Self::Scalar>;
}
/// Unary operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
/// Negate: y = -x
Negate,
/// Absolute value: y = |x|
Abs,
/// Square: y = x²
Square,
/// Square root: y = √x
Sqrt,
/// Reciprocal: y = 1/x
Reciprocal,
/// Exponential: y = eˣ
Exp,
/// Natural log: y = ln(x)
Log,
/// Sine: y = sin(x)
Sin,
/// Cosine: y = cos(x)
Cos,
/// Tangent: y = tan(x)
Tan,
/// `ReLU`: max(0, x)
ReLU,
/// Sigmoid: 1 / (1 + e⁻ˣ)
Sigmoid,
/// Tanh: (eˣ - e⁻ˣ) / (eˣ + e⁻ˣ)
Tanh,
/// GELU: x * Φ(x) where Φ is standard normal CDF
GELU,
}
/// Binary operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryOp {
/// Addition: z = x + y
Add,
/// Subtraction: z = x - y
Sub,
/// Multiplication: z = x * y
Mul,
/// Division: z = x / y
Div,
/// Power: z = xʸ
Pow,
/// Maximum: z = max(x, y)
Max,
/// Minimum: z = min(x, y)
Min,
}
/// Reduction operation type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReduceOp {
/// Sum reduction: ∑x
Sum,
/// Mean reduction: mean(x)
Mean,
/// Max reduction: max(x)
Max,
/// Min reduction: min(x)
Min,
/// Product reduction: ∏x
Prod,
}
/// Hardware-agnostic tensor descriptor
///
/// Describes tensor metadata without storing data
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TensorDescriptor {
/// Shape (dimensions)
pub shape: Vec<usize>,
/// Data type
pub dtype: DType,
/// Strides (for non-contiguous tensors)
pub strides: Vec<usize>,
/// Total number of elements
pub numel: usize,
}
impl TensorDescriptor {
/// Create a new tensor descriptor from shape and data type.
#[must_use]
pub fn new(shape: Vec<usize>, dtype: DType) -> Self {
let numel = shape.iter().product();
let strides = Self::compute_strides(&shape);
Self {
shape,
dtype,
strides,
numel,
}
}
/// Compute strides for a contiguous tensor of the given shape.
fn compute_strides(shape: &[usize]) -> Vec<usize> {
let mut strides = vec![1; shape.len()];
for i in (0..shape.len().saturating_sub(1)).rev() {
strides[i] = strides[i + 1] * shape[i + 1];
}
strides
}
/// Returns the rank (number of dimensions).
#[must_use]
pub fn rank(&self) -> usize {
self.shape.len()
}
/// Returns `true` if the tensor is a scalar (single element).
#[must_use]
pub fn is_scalar(&self) -> bool {
self.numel == 1
}
/// Returns `true` if the tensor is a vector (rank 1).
#[must_use]
pub fn is_vector(&self) -> bool {
self.rank() == 1
}
/// Returns `true` if the tensor is a matrix (rank 2).
#[must_use]
pub fn is_matrix(&self) -> bool {
self.rank() == 2
}
}
/// Data type enumeration covering the full precision continuum.
///
/// Extends from packed 1-bit binary through native 64-bit types.
/// New sub-f32 types map to the precision tier storage formats.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DType {
/// Packed 1-bit binary (32 values per u32).
Binary,
/// Packed 2-bit integer (16 values per u32).
I2,
/// Packed 4-bit integer (8 values per u32).
I4,
/// Signed 8-bit integer.
I8,
/// 8-bit float E4M3 (OFP): 3-bit mantissa, 4-bit exponent.
F8E4M3,
/// 8-bit float E5M2 (OFP): 2-bit mantissa, 5-bit exponent.
F8E5M2,
/// 16-bit bfloat (Google Brain): f32 exponent range, 7-bit mantissa.
Bf16,
/// 16-bit IEEE half precision (binary16).
F16,
/// 32-bit floating point
F32,
/// 64-bit floating point
F64,
/// 32-bit signed integer
I32,
/// 64-bit signed integer
I64,
/// 32-bit unsigned integer
U32,
/// 64-bit unsigned integer
U64,
/// Boolean
Bool,
}
impl DType {
/// Returns the size in bytes of a single element of this type.
///
/// For sub-byte types (Binary, I2, I4), returns 1 as the minimum
/// addressable unit. Actual packing is handled at the buffer level.
#[must_use]
pub fn size_bytes(&self) -> usize {
match self {
Self::Binary | Self::I2 | Self::I4 | Self::I8 => 1,
Self::F8E4M3 | Self::F8E5M2 => 1,
Self::Bf16 | Self::F16 => 2,
Self::F32 | Self::I32 | Self::U32 => 4,
Self::F64 | Self::I64 | Self::U64 => 8,
Self::Bool => 1,
}
}
/// Whether this is a floating-point type (including reduced and extended).
#[must_use]
pub fn is_float(&self) -> bool {
matches!(
self,
Self::F8E4M3 | Self::F8E5M2 | Self::Bf16 | Self::F16 | Self::F32 | Self::F64
)
}
/// Whether this is an integer type (including sub-byte packed).
#[must_use]
pub fn is_integer(&self) -> bool {
matches!(
self,
Self::Binary
| Self::I2
| Self::I4
| Self::I8
| Self::I32
| Self::I64
| Self::U32
| Self::U64
)
}
/// Whether this is a sub-byte packed format.
#[must_use]
pub fn is_packed(&self) -> bool {
matches!(self, Self::Binary | Self::I2 | Self::I4)
}
}
/// Math operation graph node
///
/// Represents a node in the computation graph
#[derive(Debug, Clone)]
pub struct OpNode {
/// Operation
pub op: MathOp,
/// Input tensor descriptors
pub inputs: Vec<TensorDescriptor>,
/// Output tensor descriptor
pub output: TensorDescriptor,
/// Operation name (for debugging)
pub name: Option<String>,
}
impl OpNode {
/// Create a new operation node.
#[must_use]
pub fn new(op: MathOp, inputs: Vec<TensorDescriptor>, output: TensorDescriptor) -> Self {
Self {
op,
inputs,
output,
name: None,
}
}
/// Set the operation name for debugging.
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_tensor_descriptor_creation() {
let desc = TensorDescriptor::new(vec![2, 3, 4], DType::F32);
assert_eq!(desc.shape, vec![2, 3, 4]);
assert_eq!(desc.numel, 24);
assert_eq!(desc.rank(), 3);
assert!(!desc.is_scalar());
assert!(!desc.is_vector());
assert!(!desc.is_matrix());
}
#[test]
fn test_dtype_size() {
assert_eq!(DType::Binary.size_bytes(), 1);
assert_eq!(DType::I2.size_bytes(), 1);
assert_eq!(DType::I4.size_bytes(), 1);
assert_eq!(DType::I8.size_bytes(), 1);
assert_eq!(DType::F8E4M3.size_bytes(), 1);
assert_eq!(DType::F8E5M2.size_bytes(), 1);
assert_eq!(DType::Bf16.size_bytes(), 2);
assert_eq!(DType::F16.size_bytes(), 2);
assert_eq!(DType::F32.size_bytes(), 4);
assert_eq!(DType::F64.size_bytes(), 8);
assert_eq!(DType::Bool.size_bytes(), 1);
}
#[test]
fn test_dtype_classification() {
assert!(DType::F32.is_float());
assert!(DType::Bf16.is_float());
assert!(DType::F8E4M3.is_float());
assert!(!DType::I32.is_float());
assert!(!DType::Binary.is_float());
assert!(DType::I32.is_integer());
assert!(DType::Binary.is_integer());
assert!(DType::I2.is_integer());
assert!(!DType::F32.is_integer());
assert!(DType::Binary.is_packed());
assert!(DType::I2.is_packed());
assert!(DType::I4.is_packed());
assert!(!DType::I8.is_packed());
}
#[test]
fn test_tensor_shapes() {
let scalar = TensorDescriptor::new(vec![1], DType::F32);
assert!(scalar.is_scalar());
let vector = TensorDescriptor::new(vec![10], DType::F32);
assert!(vector.is_vector());
let matrix = TensorDescriptor::new(vec![3, 4], DType::F32);
assert!(matrix.is_matrix());
}
#[test]
fn test_math_op_clone() {
let op = MathOp::Add;
let cloned = op.clone();
assert_eq!(op, cloned);
}
}