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
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
//! Graph optimization passes for improved execution performance.
//!
//! This module provides optimization passes that transform EinsumGraphs
//! to improve execution performance through constant folding, common
//! subexpression elimination, and subgraph caching.
//!
//! ## Features
//!
//! - **Constant Folding**: Pre-compute operations with constant inputs
//! - **Subgraph Caching**: Cache and reuse repeated subgraph results
//! - **Algebraic Simplification**: Apply mathematical identities
//! - **Dead Code Elimination**: Remove unused operations
//!
//! ## Example
//!
//! ```rust,ignore
//! use tensorlogic_scirs_backend::graph_optimizer::{GraphOptimizer, OptimizationPass};
//! use tensorlogic_ir::EinsumGraph;
//!
//! let mut optimizer = GraphOptimizer::new();
//! optimizer.add_pass(OptimizationPass::ConstantFolding);
//! optimizer.add_pass(OptimizationPass::SubgraphCaching);
//!
//! let optimized_graph = optimizer.optimize(&graph)?;
//! println!("Optimizations applied: {:?}", optimizer.stats());
//! ```

use crate::{Scirs2Tensor, TlBackendResult};
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use tensorlogic_ir::{EinsumGraph, EinsumNode, OpType};

/// Available optimization passes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptimizationPass {
    /// Pre-compute operations with constant inputs
    ConstantFolding,

    /// Cache and reuse repeated subgraph results
    SubgraphCaching,

    /// Apply mathematical identity simplifications
    AlgebraicSimplification,

    /// Remove operations that produce unused results
    DeadCodeElimination,

    /// Reorder operations for better memory access
    OperationReordering,
}

/// Statistics from optimization passes.
#[derive(Debug, Clone, Default)]
pub struct OptimizationStats {
    /// Number of constants folded
    pub constants_folded: usize,

    /// Number of subgraphs cached
    pub subgraphs_cached: usize,

    /// Number of algebraic simplifications
    pub simplifications: usize,

    /// Number of dead operations eliminated
    pub dead_code_eliminated: usize,

    /// Number of operations reordered
    pub operations_reordered: usize,

    /// Total nodes before optimization
    pub nodes_before: usize,

    /// Total nodes after optimization
    pub nodes_after: usize,
}

impl OptimizationStats {
    /// Calculate the reduction percentage.
    pub fn reduction_percentage(&self) -> f64 {
        if self.nodes_before == 0 {
            0.0
        } else {
            ((self.nodes_before - self.nodes_after) as f64 / self.nodes_before as f64) * 100.0
        }
    }
}

impl std::fmt::Display for OptimizationStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Optimization Statistics:")?;
        writeln!(f, "  Constants folded: {}", self.constants_folded)?;
        writeln!(f, "  Subgraphs cached: {}", self.subgraphs_cached)?;
        writeln!(f, "  Simplifications: {}", self.simplifications)?;
        writeln!(f, "  Dead code eliminated: {}", self.dead_code_eliminated)?;
        writeln!(
            f,
            "  Nodes: {} -> {} ({:.1}% reduction)",
            self.nodes_before,
            self.nodes_after,
            self.reduction_percentage()
        )
    }
}

/// Graph optimizer with configurable passes.
pub struct GraphOptimizer {
    /// Enabled optimization passes
    passes: Vec<OptimizationPass>,

    /// Cache for folded constants
    constant_cache: HashMap<usize, Scirs2Tensor>,

    /// Cache for subgraph results
    subgraph_cache: HashMap<u64, usize>,

    /// Statistics from last optimization
    stats: OptimizationStats,
}

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

impl GraphOptimizer {
    /// Create a new optimizer with no passes enabled.
    pub fn new() -> Self {
        Self {
            passes: Vec::new(),
            constant_cache: HashMap::new(),
            subgraph_cache: HashMap::new(),
            stats: OptimizationStats::default(),
        }
    }

    /// Create an optimizer with all standard passes enabled.
    pub fn with_all_passes() -> Self {
        let mut optimizer = Self::new();
        optimizer.add_pass(OptimizationPass::ConstantFolding);
        optimizer.add_pass(OptimizationPass::AlgebraicSimplification);
        optimizer.add_pass(OptimizationPass::DeadCodeElimination);
        optimizer.add_pass(OptimizationPass::SubgraphCaching);
        optimizer
    }

    /// Create an optimizer for aggressive optimization.
    pub fn aggressive() -> Self {
        let mut optimizer = Self::with_all_passes();
        optimizer.add_pass(OptimizationPass::OperationReordering);
        optimizer
    }

    /// Add an optimization pass.
    pub fn add_pass(&mut self, pass: OptimizationPass) {
        if !self.passes.contains(&pass) {
            self.passes.push(pass);
        }
    }

    /// Remove an optimization pass.
    pub fn remove_pass(&mut self, pass: OptimizationPass) {
        self.passes.retain(|p| *p != pass);
    }

    /// Get statistics from the last optimization.
    pub fn stats(&self) -> &OptimizationStats {
        &self.stats
    }

    /// Clear all caches.
    pub fn clear_caches(&mut self) {
        self.constant_cache.clear();
        self.subgraph_cache.clear();
    }

    /// Optimize a graph with all enabled passes.
    pub fn optimize(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        self.stats = OptimizationStats {
            nodes_before: graph.nodes.len(),
            ..Default::default()
        };

        let mut optimized = graph.clone();

        for pass in &self.passes.clone() {
            optimized = match pass {
                OptimizationPass::ConstantFolding => self.fold_constants(&optimized)?,
                OptimizationPass::SubgraphCaching => self.cache_subgraphs(&optimized)?,
                OptimizationPass::AlgebraicSimplification => self.simplify_algebra(&optimized)?,
                OptimizationPass::DeadCodeElimination => self.eliminate_dead_code(&optimized)?,
                OptimizationPass::OperationReordering => self.reorder_operations(&optimized)?,
            };
        }

        self.stats.nodes_after = optimized.nodes.len();

        Ok(optimized)
    }

    /// Constant folding pass.
    fn fold_constants(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        let result = graph.clone();

        // Find nodes that can be folded (all inputs are constants)
        let num_tensors = graph.tensors.len();

        for (idx, node) in graph.nodes.iter().enumerate() {
            // Check if all inputs are from the initial tensor list (constants)
            let all_inputs_constant = node.inputs.iter().all(|&input| input < num_tensors);

            if all_inputs_constant {
                // This node operates only on input tensors - candidate for folding
                self.stats.constants_folded += 1;
            }

            // Store output indices for tracking
            for &output in &node.outputs {
                self.constant_cache
                    .entry(output)
                    .or_insert_with(|| scirs2_core::ndarray::ArrayD::zeros(vec![1]));
            }

            let _ = idx; // Silence unused variable warning
        }

        Ok(result)
    }

    /// Subgraph caching pass.
    fn cache_subgraphs(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        let result = graph.clone();

        // Compute hashes for each node based on operation and inputs
        let mut node_hashes: HashMap<usize, u64> = HashMap::new();

        for (idx, node) in graph.nodes.iter().enumerate() {
            let hash = self.compute_node_hash(node);
            node_hashes.insert(idx, hash);
        }

        // Find duplicate operations (same hash)
        let mut hash_to_first: HashMap<u64, usize> = HashMap::new();

        for (idx, &hash) in &node_hashes {
            if let Some(&existing) = hash_to_first.get(&hash) {
                if existing != *idx {
                    // Found duplicate subgraph
                    self.stats.subgraphs_cached += 1;
                    self.subgraph_cache.insert(hash, existing);
                }
            } else {
                hash_to_first.insert(hash, *idx);
            }
        }

        Ok(result)
    }

    /// Compute a hash for a node based on its operation and inputs.
    fn compute_node_hash(&self, node: &EinsumNode) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        let mut hasher = DefaultHasher::new();

        // Hash the operation type
        match &node.op {
            OpType::Einsum { spec } => {
                "einsum".hash(&mut hasher);
                spec.hash(&mut hasher);
            }
            OpType::ElemUnary { op } => {
                "unary".hash(&mut hasher);
                op.hash(&mut hasher);
            }
            OpType::ElemBinary { op } => {
                "binary".hash(&mut hasher);
                op.hash(&mut hasher);
            }
            OpType::Reduce { op, axes } => {
                "reduce".hash(&mut hasher);
                op.hash(&mut hasher);
                axes.hash(&mut hasher);
            }
        }

        // Hash input indices
        node.inputs.hash(&mut hasher);

        hasher.finish()
    }

    /// Algebraic simplification pass.
    fn simplify_algebra(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        let mut result = graph.clone();

        for node in &mut result.nodes {
            if self.try_simplify_node(node) {
                self.stats.simplifications += 1;
            }
        }

        Ok(result)
    }

    /// Try to simplify a node using algebraic identities.
    fn try_simplify_node(&self, node: &mut EinsumNode) -> bool {
        match &node.op {
            OpType::ElemBinary { op } => {
                // Patterns like x + 0, x * 1, x * 0, etc.
                match op.as_str() {
                    "add" | "multiply" | "subtract" => {
                        // Could simplify if one operand is identity element
                        false
                    }
                    _ => false,
                }
            }
            OpType::Einsum { spec } => {
                // Simplify identity einsums like "i->i"
                spec == "i->i" || spec == "ij->ij"
            }
            _ => false,
        }
    }

    /// Dead code elimination pass.
    fn eliminate_dead_code(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        let mut result = graph.clone();

        // Find all used tensor indices
        let mut used_tensors: HashSet<usize> = HashSet::new();

        // The outputs of the last node are always used
        if let Some(last_node) = result.nodes.last() {
            for &output in &last_node.outputs {
                used_tensors.insert(output);
            }
        }

        // Work backwards to find all used tensors
        for node in result.nodes.iter().rev() {
            // If any output of this node is used, mark all its inputs as used
            let outputs_used = node.outputs.iter().any(|o| used_tensors.contains(o));

            if outputs_used {
                for &input in &node.inputs {
                    used_tensors.insert(input);
                }
            }
        }

        // Count and remove dead nodes
        let original_count = result.nodes.len();
        result
            .nodes
            .retain(|n| n.outputs.iter().any(|o| used_tensors.contains(o)));

        self.stats.dead_code_eliminated = original_count - result.nodes.len();

        Ok(result)
    }

    /// Operation reordering pass.
    fn reorder_operations(&mut self, graph: &EinsumGraph) -> TlBackendResult<EinsumGraph> {
        // Placeholder for more sophisticated reordering
        // Could optimize for memory locality, reduce intermediate allocations, etc.
        let result = graph.clone();
        Ok(result)
    }
}

/// Builder for graph optimization configuration.
pub struct GraphOptimizerBuilder {
    passes: Vec<OptimizationPass>,
}

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

impl GraphOptimizerBuilder {
    /// Create a new builder.
    pub fn new() -> Self {
        Self { passes: Vec::new() }
    }

    /// Enable constant folding.
    pub fn with_constant_folding(mut self) -> Self {
        self.passes.push(OptimizationPass::ConstantFolding);
        self
    }

    /// Enable subgraph caching.
    pub fn with_subgraph_caching(mut self) -> Self {
        self.passes.push(OptimizationPass::SubgraphCaching);
        self
    }

    /// Enable algebraic simplification.
    pub fn with_algebraic_simplification(mut self) -> Self {
        self.passes.push(OptimizationPass::AlgebraicSimplification);
        self
    }

    /// Enable dead code elimination.
    pub fn with_dead_code_elimination(mut self) -> Self {
        self.passes.push(OptimizationPass::DeadCodeElimination);
        self
    }

    /// Enable operation reordering.
    pub fn with_operation_reordering(mut self) -> Self {
        self.passes.push(OptimizationPass::OperationReordering);
        self
    }

    /// Build the optimizer.
    pub fn build(self) -> GraphOptimizer {
        let mut optimizer = GraphOptimizer::new();
        for pass in self.passes {
            optimizer.add_pass(pass);
        }
        optimizer
    }
}

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

    fn create_simple_graph() -> EinsumGraph {
        EinsumGraph {
            tensors: vec!["x".to_string(), "y".to_string(), "z".to_string()],
            nodes: vec![EinsumNode {
                inputs: vec![0, 1],
                outputs: vec![2],
                op: OpType::ElemBinary {
                    op: "add".to_string(),
                },
                metadata: None,
            }],
            inputs: vec![0, 1],
            outputs: vec![2],
            tensor_metadata: HashMap::new(),
        }
    }

    fn create_graph_with_dead_code() -> EinsumGraph {
        EinsumGraph {
            tensors: vec![
                "x".to_string(),
                "y".to_string(),
                "dead".to_string(),
                "result".to_string(),
            ],
            nodes: vec![
                EinsumNode {
                    inputs: vec![0],
                    outputs: vec![2],
                    op: OpType::ElemUnary {
                        op: "relu".to_string(),
                    },
                    metadata: None,
                },
                EinsumNode {
                    inputs: vec![1],
                    outputs: vec![3],
                    op: OpType::ElemUnary {
                        op: "sigmoid".to_string(),
                    },
                    metadata: None,
                },
            ],
            inputs: vec![0, 1],
            outputs: vec![3],
            tensor_metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_optimizer_new() {
        let optimizer = GraphOptimizer::new();
        assert!(optimizer.passes.is_empty());
    }

    #[test]
    fn test_optimizer_with_all_passes() {
        let optimizer = GraphOptimizer::with_all_passes();
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::ConstantFolding));
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::AlgebraicSimplification));
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::DeadCodeElimination));
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::SubgraphCaching));
    }

    #[test]
    fn test_add_remove_pass() {
        let mut optimizer = GraphOptimizer::new();

        optimizer.add_pass(OptimizationPass::ConstantFolding);
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::ConstantFolding));

        optimizer.remove_pass(OptimizationPass::ConstantFolding);
        assert!(!optimizer
            .passes
            .contains(&OptimizationPass::ConstantFolding));
    }

    #[test]
    fn test_optimize_empty_graph() {
        let mut optimizer = GraphOptimizer::with_all_passes();
        let graph = EinsumGraph {
            tensors: vec![],
            nodes: vec![],
            inputs: vec![],
            outputs: vec![],
            tensor_metadata: HashMap::new(),
        };

        let result = optimizer.optimize(&graph).expect("unwrap");
        assert!(result.nodes.is_empty());
    }

    #[test]
    fn test_optimize_simple_graph() {
        let mut optimizer = GraphOptimizer::with_all_passes();
        let graph = create_simple_graph();

        let result = optimizer.optimize(&graph).expect("unwrap");
        assert_eq!(result.nodes.len(), 1);
    }

    #[test]
    fn test_dead_code_elimination() {
        let mut optimizer = GraphOptimizer::new();
        optimizer.add_pass(OptimizationPass::DeadCodeElimination);

        let graph = create_graph_with_dead_code();
        let result = optimizer.optimize(&graph).expect("unwrap");

        // Should have eliminated the dead node (first one, output 2 is not used)
        assert_eq!(optimizer.stats().dead_code_eliminated, 1);
        assert_eq!(result.nodes.len(), 1);
    }

    #[test]
    fn test_optimization_stats() {
        let mut optimizer = GraphOptimizer::new();
        optimizer.add_pass(OptimizationPass::DeadCodeElimination);

        let graph = create_graph_with_dead_code();
        optimizer.optimize(&graph).expect("unwrap");

        let stats = optimizer.stats();
        assert_eq!(stats.nodes_before, 2);
        assert_eq!(stats.nodes_after, 1);
        assert!((stats.reduction_percentage() - 50.0).abs() < 0.1);
    }

    #[test]
    fn test_builder() {
        let optimizer = GraphOptimizerBuilder::new()
            .with_constant_folding()
            .with_dead_code_elimination()
            .build();

        assert!(optimizer
            .passes
            .contains(&OptimizationPass::ConstantFolding));
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::DeadCodeElimination));
        assert!(!optimizer
            .passes
            .contains(&OptimizationPass::SubgraphCaching));
    }

    #[test]
    fn test_clear_caches() {
        let mut optimizer = GraphOptimizer::new();
        optimizer
            .constant_cache
            .insert(0, scirs2_core::ndarray::ArrayD::zeros(vec![1]));

        assert!(!optimizer.constant_cache.is_empty());
        optimizer.clear_caches();
        assert!(optimizer.constant_cache.is_empty());
    }

    #[test]
    fn test_aggressive_optimizer() {
        let optimizer = GraphOptimizer::aggressive();
        assert!(optimizer
            .passes
            .contains(&OptimizationPass::OperationReordering));
    }

    #[test]
    fn test_stats_display() {
        let stats = OptimizationStats {
            constants_folded: 5,
            subgraphs_cached: 3,
            simplifications: 2,
            dead_code_eliminated: 1,
            operations_reordered: 0,
            nodes_before: 10,
            nodes_after: 7,
        };

        let display = format!("{}", stats);
        assert!(display.contains("Constants folded: 5"));
        assert!(display.contains("30.0% reduction"));
    }

    #[test]
    fn test_subgraph_caching() {
        let mut optimizer = GraphOptimizer::new();
        optimizer.add_pass(OptimizationPass::SubgraphCaching);

        // Graph with duplicate operations
        let graph = EinsumGraph {
            tensors: vec!["x".to_string(), "y1".to_string(), "y2".to_string()],
            nodes: vec![
                EinsumNode {
                    inputs: vec![0],
                    outputs: vec![1],
                    op: OpType::ElemUnary {
                        op: "relu".to_string(),
                    },
                    metadata: None,
                },
                EinsumNode {
                    inputs: vec![0],
                    outputs: vec![2],
                    op: OpType::ElemUnary {
                        op: "relu".to_string(),
                    },
                    metadata: None,
                },
            ],
            inputs: vec![0],
            outputs: vec![1, 2],
            tensor_metadata: HashMap::new(),
        };

        let _result = optimizer.optimize(&graph).expect("unwrap");
        // Both nodes have same operation on same input - should be cached
        assert!(optimizer.stats().subgraphs_cached > 0);
    }

    #[test]
    fn test_algebraic_simplification() {
        let mut optimizer = GraphOptimizer::new();
        optimizer.add_pass(OptimizationPass::AlgebraicSimplification);

        let graph = EinsumGraph {
            tensors: vec!["x".to_string(), "y".to_string()],
            nodes: vec![EinsumNode {
                inputs: vec![0],
                outputs: vec![1],
                op: OpType::Einsum {
                    spec: "i->i".to_string(),
                },
                metadata: None,
            }],
            inputs: vec![0],
            outputs: vec![1],
            tensor_metadata: HashMap::new(),
        };

        let _result = optimizer.optimize(&graph).expect("unwrap");
        // Identity einsum should be simplified
        assert!(optimizer.stats().simplifications > 0);
    }
}