Skip to main content

trustformers_mobile/optimization/
graph_optimizer.rs

1//! Graph Optimization Module
2//!
3//! Provides graph-level optimizations for mobile inference including:
4//! - Constant folding
5//! - Dead code elimination
6//! - Common subexpression elimination
7//! - Algebraic simplification
8
9use super::{ComputationGraph, GraphOperator, KernelType};
10use std::collections::{HashMap, HashSet, VecDeque};
11use trustformers_core::error::{CoreError, Result};
12use trustformers_core::Tensor;
13use trustformers_core::TrustformersError;
14
15/// Optimization pass types
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum OptimizationPass {
18    ConstantFolding,
19    DeadCodeElimination,
20    CommonSubexpressionElimination,
21    AlgebraicSimplification,
22    StrengthReduction,
23    LoopInvariantCodeMotion,
24}
25
26/// Graph rewriter for applying transformations
27pub struct GraphRewriter {
28    transformations: Vec<Box<dyn GraphTransformation>>,
29}
30
31/// Trait for graph transformations
32pub trait GraphTransformation: Send + Sync {
33    /// Apply transformation to graph
34    fn apply(&self, graph: &mut ComputationGraph) -> Result<bool>;
35
36    /// Get transformation name
37    fn name(&self) -> &str;
38}
39
40/// Graph optimizer
41pub struct GraphOptimizer {
42    passes: Vec<OptimizationPass>,
43    rewriter: GraphRewriter,
44    stats: OptimizationStats,
45}
46
47#[derive(Debug, Default)]
48struct OptimizationStats {
49    constants_folded: usize,
50    dead_code_eliminated: usize,
51    cse_eliminated: usize,
52    algebraic_simplified: usize,
53}
54
55impl Default for GraphOptimizer {
56    fn default() -> Self {
57        Self::new()
58    }
59}
60
61impl GraphOptimizer {
62    /// Create new graph optimizer
63    pub fn new() -> Self {
64        let passes = vec![
65            OptimizationPass::ConstantFolding,
66            OptimizationPass::DeadCodeElimination,
67            OptimizationPass::CommonSubexpressionElimination,
68            OptimizationPass::AlgebraicSimplification,
69        ];
70
71        let transformations: Vec<Box<dyn GraphTransformation>> = vec![
72            Box::new(ConstantFolding::new()),
73            Box::new(DeadCodeElimination::new()),
74            Box::new(CommonSubexpressionElimination::new()),
75            Box::new(AlgebraicSimplification::new()),
76        ];
77
78        Self {
79            passes,
80            rewriter: GraphRewriter { transformations },
81            stats: OptimizationStats::default(),
82        }
83    }
84
85    /// Apply all optimization passes
86    pub fn optimize(&mut self, graph: &mut ComputationGraph) -> Result<()> {
87        let passes = self.passes.clone();
88        for pass in passes {
89            match pass {
90                OptimizationPass::ConstantFolding => self.apply_constant_folding(graph)?,
91                OptimizationPass::DeadCodeElimination => self.apply_dead_code_elimination(graph)?,
92                OptimizationPass::CommonSubexpressionElimination => self.apply_cse(graph)?,
93                OptimizationPass::AlgebraicSimplification => {
94                    self.apply_algebraic_simplification(graph)?
95                },
96                _ => {},
97            }
98        }
99        Ok(())
100    }
101
102    /// Apply constant folding optimization
103    pub fn apply_constant_folding(&mut self, graph: &mut ComputationGraph) -> Result<()> {
104        let folding = ConstantFolding::new();
105        if folding.apply(graph)? {
106            self.stats.constants_folded += 1;
107        }
108        Ok(())
109    }
110
111    /// Apply dead code elimination
112    pub fn apply_dead_code_elimination(&mut self, graph: &mut ComputationGraph) -> Result<()> {
113        let dce = DeadCodeElimination::new();
114        if dce.apply(graph)? {
115            self.stats.dead_code_eliminated += 1;
116        }
117        Ok(())
118    }
119
120    /// Apply common subexpression elimination
121    pub fn apply_cse(&mut self, graph: &mut ComputationGraph) -> Result<()> {
122        let cse = CommonSubexpressionElimination::new();
123        if cse.apply(graph)? {
124            self.stats.cse_eliminated += 1;
125        }
126        Ok(())
127    }
128
129    /// Apply algebraic simplification
130    pub fn apply_algebraic_simplification(&mut self, graph: &mut ComputationGraph) -> Result<()> {
131        let simplify = AlgebraicSimplification::new();
132        if simplify.apply(graph)? {
133            self.stats.algebraic_simplified += 1;
134        }
135        Ok(())
136    }
137}
138
139/// Constant folding optimization
140pub struct ConstantFolding {
141    constant_values: HashMap<String, Tensor>,
142}
143
144impl Default for ConstantFolding {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150impl ConstantFolding {
151    pub fn new() -> Self {
152        Self {
153            constant_values: HashMap::new(),
154        }
155    }
156
157    /// Check if operator has all constant inputs
158    fn has_constant_inputs(&self, op: &GraphOperator, graph: &ComputationGraph) -> bool {
159        op.inputs
160            .iter()
161            .all(|input| self.constant_values.contains_key(input) || self.is_constant_tensor(input))
162    }
163
164    /// Check if tensor is constant
165    fn is_constant_tensor(&self, name: &str) -> bool {
166        // Check if tensor name indicates it's a constant (e.g., weights, biases)
167        name.contains("weight") || name.contains("bias") || name.starts_with("const_")
168    }
169
170    /// Evaluate operator with constant inputs
171    fn evaluate_constant_op(&mut self, op: &GraphOperator) -> Result<Option<Tensor>> {
172        match &op.kernel {
173            KernelType::Linear => {
174                // Can fold if both input and weights are constant
175                if op.inputs.len() >= 2 {
176                    // Simplified - would need actual computation
177                    Ok(None)
178                } else {
179                    Ok(None)
180                }
181            },
182            KernelType::Custom(name) if name == "Add" => {
183                // Can fold constant additions
184                if op.inputs.len() == 2 {
185                    // Simplified - would need actual computation
186                    Ok(None)
187                } else {
188                    Ok(None)
189                }
190            },
191            _ => Ok(None),
192        }
193    }
194}
195
196impl GraphTransformation for ConstantFolding {
197    fn apply(&self, graph: &mut ComputationGraph) -> Result<bool> {
198        let mut modified = false;
199        let mut const_folding = ConstantFolding::new();
200
201        // Find operators that can be constant folded
202        let mut folded_ops = Vec::new();
203
204        for (idx, op) in graph.operators.iter().enumerate() {
205            if const_folding.has_constant_inputs(op, graph) {
206                if let Some(result) = const_folding.evaluate_constant_op(op)? {
207                    // Store the constant result
208                    const_folding.constant_values.insert(op.outputs[0].clone(), result);
209                    folded_ops.push(idx);
210                    modified = true;
211                }
212            }
213        }
214
215        // Replace folded operators with constant nodes
216        for idx in folded_ops.iter().rev() {
217            let op = &graph.operators[*idx];
218            let const_name = format!("const_{}", op.outputs[0]);
219
220            // Create constant operator
221            let const_op = GraphOperator {
222                id: op.id,
223                kernel: KernelType::Custom("Constant".to_string()),
224                inputs: vec![],
225                outputs: vec![const_name],
226                input_shapes: vec![],
227                output_shape: op.output_shape.clone(),
228                cache_hints: None,
229            };
230
231            graph.operators[*idx] = const_op;
232        }
233
234        Ok(modified)
235    }
236
237    fn name(&self) -> &str {
238        "ConstantFolding"
239    }
240}
241
242/// Dead code elimination
243pub struct DeadCodeElimination;
244
245impl Default for DeadCodeElimination {
246    fn default() -> Self {
247        Self::new()
248    }
249}
250
251impl DeadCodeElimination {
252    pub fn new() -> Self {
253        Self
254    }
255
256    /// Find operators whose outputs are not used
257    fn find_dead_operators(&self, graph: &ComputationGraph) -> HashSet<usize> {
258        let mut used_tensors = HashSet::new();
259        let mut dead_operators = HashSet::new();
260
261        // Mark all input tensors as used
262        for op in &graph.operators {
263            for input in &op.inputs {
264                used_tensors.insert(input.clone());
265            }
266        }
267
268        // Find operators whose outputs are not used
269        for (idx, op) in graph.operators.iter().enumerate() {
270            let outputs_used = op.outputs.iter().any(|output| used_tensors.contains(output));
271
272            if !outputs_used && !self.has_side_effects(op) {
273                dead_operators.insert(idx);
274            }
275        }
276
277        dead_operators
278    }
279
280    /// Check if operator has side effects
281    fn has_side_effects(&self, op: &GraphOperator) -> bool {
282        // Operators that modify state or have other side effects
283        matches!(op.kernel, KernelType::Custom(ref name) if name.contains("inplace") || name.contains("update"))
284    }
285}
286
287impl GraphTransformation for DeadCodeElimination {
288    fn apply(&self, graph: &mut ComputationGraph) -> Result<bool> {
289        let dead_ops = self.find_dead_operators(graph);
290
291        if dead_ops.is_empty() {
292            return Ok(false);
293        }
294
295        // Remove dead operators (in reverse order to maintain indices)
296        let mut indices: Vec<_> = dead_ops.into_iter().collect();
297        indices.sort_by(|a, b| b.cmp(a));
298
299        for idx in indices {
300            graph.operators.remove(idx);
301
302            // Update edges
303            graph.edges.retain(|edge| edge.from != idx && edge.to != idx);
304
305            // Update edge indices
306            for edge in &mut graph.edges {
307                if edge.from > idx {
308                    edge.from -= 1;
309                }
310                if edge.to > idx {
311                    edge.to -= 1;
312                }
313            }
314        }
315
316        Ok(true)
317    }
318
319    fn name(&self) -> &str {
320        "DeadCodeElimination"
321    }
322}
323
324/// Common subexpression elimination
325pub struct CommonSubexpressionElimination;
326
327impl Default for CommonSubexpressionElimination {
328    fn default() -> Self {
329        Self::new()
330    }
331}
332
333impl CommonSubexpressionElimination {
334    pub fn new() -> Self {
335        Self
336    }
337
338    /// Find duplicate computations
339    fn find_duplicate_ops(&self, graph: &ComputationGraph) -> Vec<(usize, usize)> {
340        let mut duplicates = Vec::new();
341
342        for i in 0..graph.operators.len() {
343            for j in i + 1..graph.operators.len() {
344                if self.ops_are_equivalent(&graph.operators[i], &graph.operators[j]) {
345                    duplicates.push((i, j));
346                }
347            }
348        }
349
350        duplicates
351    }
352
353    /// Check if two operators compute the same thing
354    fn ops_are_equivalent(&self, op1: &GraphOperator, op2: &GraphOperator) -> bool {
355        // Same kernel type
356        if std::mem::discriminant(&op1.kernel) != std::mem::discriminant(&op2.kernel) {
357            return false;
358        }
359
360        // Same inputs (order matters for non-commutative ops)
361        if op1.inputs != op2.inputs {
362            return false;
363        }
364
365        // Same shapes
366        if op1.input_shapes != op2.input_shapes || op1.output_shape != op2.output_shape {
367            return false;
368        }
369
370        true
371    }
372}
373
374impl GraphTransformation for CommonSubexpressionElimination {
375    fn apply(&self, graph: &mut ComputationGraph) -> Result<bool> {
376        let duplicates = self.find_duplicate_ops(graph);
377
378        if duplicates.is_empty() {
379            return Ok(false);
380        }
381
382        // Replace duplicate computations
383        for (original, duplicate) in duplicates.iter().rev() {
384            let original_output = graph.operators[*original].outputs[0].clone();
385            let duplicate_output = graph.operators[*duplicate].outputs[0].clone();
386
387            // Redirect all uses of duplicate output to original output
388            for op in &mut graph.operators {
389                for input in &mut op.inputs {
390                    if input == &duplicate_output {
391                        *input = original_output.clone();
392                    }
393                }
394            }
395
396            // Remove duplicate operator
397            graph.operators.remove(*duplicate);
398
399            // Update edges
400            for edge in &mut graph.edges {
401                if edge.tensor_name == duplicate_output {
402                    edge.tensor_name = original_output.clone();
403                }
404            }
405        }
406
407        Ok(true)
408    }
409
410    fn name(&self) -> &str {
411        "CommonSubexpressionElimination"
412    }
413}
414
415/// Algebraic simplification
416pub struct AlgebraicSimplification;
417
418impl Default for AlgebraicSimplification {
419    fn default() -> Self {
420        Self::new()
421    }
422}
423
424impl AlgebraicSimplification {
425    pub fn new() -> Self {
426        Self
427    }
428
429    /// Apply algebraic identities
430    fn simplify_operator(&self, op: &GraphOperator) -> Option<GraphOperator> {
431        if let KernelType::Custom(name) = &op.kernel {
432            match name.as_str() {
433                "Mul" => {
434                    // x * 1 = x
435                    if self.is_one(&op.inputs[1]) {
436                        return Some(self.create_identity_op(op, 0));
437                    }
438                    // 1 * x = x
439                    if self.is_one(&op.inputs[0]) {
440                        return Some(self.create_identity_op(op, 1));
441                    }
442                    // x * 0 = 0
443                    if self.is_zero(&op.inputs[0]) || self.is_zero(&op.inputs[1]) {
444                        return Some(self.create_zero_op(op));
445                    }
446                },
447                "Add" => {
448                    // x + 0 = x
449                    if self.is_zero(&op.inputs[1]) {
450                        return Some(self.create_identity_op(op, 0));
451                    }
452                    // 0 + x = x
453                    if self.is_zero(&op.inputs[0]) {
454                        return Some(self.create_identity_op(op, 1));
455                    }
456                },
457                "Sub" => {
458                    // x - 0 = x
459                    if self.is_zero(&op.inputs[1]) {
460                        return Some(self.create_identity_op(op, 0));
461                    }
462                    // x - x = 0
463                    if op.inputs[0] == op.inputs[1] {
464                        return Some(self.create_zero_op(op));
465                    }
466                },
467                _ => {},
468            }
469        }
470
471        None
472    }
473
474    fn is_zero(&self, tensor_name: &str) -> bool {
475        tensor_name.contains("zero") || tensor_name == "0"
476    }
477
478    fn is_one(&self, tensor_name: &str) -> bool {
479        tensor_name.contains("one") || tensor_name == "1"
480    }
481
482    fn create_identity_op(&self, original: &GraphOperator, input_idx: usize) -> GraphOperator {
483        GraphOperator {
484            id: original.id,
485            kernel: KernelType::Custom("Identity".to_string()),
486            inputs: vec![original.inputs[input_idx].clone()],
487            outputs: original.outputs.clone(),
488            input_shapes: vec![original.input_shapes[input_idx].clone()],
489            output_shape: original.output_shape.clone(),
490            cache_hints: original.cache_hints.clone(),
491        }
492    }
493
494    fn create_zero_op(&self, original: &GraphOperator) -> GraphOperator {
495        GraphOperator {
496            id: original.id,
497            kernel: KernelType::Custom("Zero".to_string()),
498            inputs: vec![],
499            outputs: original.outputs.clone(),
500            input_shapes: vec![],
501            output_shape: original.output_shape.clone(),
502            cache_hints: original.cache_hints.clone(),
503        }
504    }
505}
506
507impl GraphTransformation for AlgebraicSimplification {
508    fn apply(&self, graph: &mut ComputationGraph) -> Result<bool> {
509        let mut modified = false;
510
511        for op in &mut graph.operators {
512            if let Some(simplified) = self.simplify_operator(op) {
513                *op = simplified;
514                modified = true;
515            }
516        }
517
518        Ok(modified)
519    }
520
521    fn name(&self) -> &str {
522        "AlgebraicSimplification"
523    }
524}
525
526/// Graph analysis utilities
527pub struct GraphAnalyzer;
528
529impl GraphAnalyzer {
530    /// Compute topological order of operators
531    pub fn topological_sort(graph: &ComputationGraph) -> Result<Vec<usize>> {
532        let mut in_degree = vec![0; graph.operators.len()];
533        let mut adj_list: Vec<Vec<usize>> = vec![vec![]; graph.operators.len()];
534
535        // Build adjacency list and in-degree count
536        for edge in &graph.edges {
537            adj_list[edge.from].push(edge.to);
538            in_degree[edge.to] += 1;
539        }
540
541        // Find nodes with no incoming edges
542        let mut queue = VecDeque::new();
543        for (idx, &degree) in in_degree.iter().enumerate() {
544            if degree == 0 {
545                queue.push_back(idx);
546            }
547        }
548
549        let mut sorted = Vec::new();
550
551        while let Some(node) = queue.pop_front() {
552            sorted.push(node);
553
554            for &neighbor in &adj_list[node] {
555                in_degree[neighbor] -= 1;
556                if in_degree[neighbor] == 0 {
557                    queue.push_back(neighbor);
558                }
559            }
560        }
561
562        if sorted.len() != graph.operators.len() {
563            return Err(TrustformersError::runtime_error("Graph contains cycles".into()).into());
564        }
565
566        Ok(sorted)
567    }
568
569    /// Find critical path through graph
570    pub fn critical_path(graph: &ComputationGraph) -> Result<Vec<usize>> {
571        let topo_order = Self::topological_sort(graph)?;
572        let mut distances = vec![0.0; graph.operators.len()];
573        let mut predecessors = vec![None; graph.operators.len()];
574
575        // Compute longest path
576        for &node in &topo_order {
577            for edge in &graph.edges {
578                if edge.from == node {
579                    let weight = 1.0; // Could be actual computation cost
580                    if distances[node] + weight > distances[edge.to] {
581                        distances[edge.to] = distances[node] + weight;
582                        predecessors[edge.to] = Some(node);
583                    }
584                }
585            }
586        }
587
588        // Find node with maximum distance
589        let end_node = distances
590            .iter()
591            .enumerate()
592            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
593            .map(|(idx, _)| idx)
594            .unwrap_or(0);
595
596        // Reconstruct path
597        let mut path = Vec::new();
598        let mut current = Some(end_node);
599
600        while let Some(node) = current {
601            path.push(node);
602            current = predecessors[node];
603        }
604
605        path.reverse();
606        Ok(path)
607    }
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613
614    #[test]
615    fn test_graph_optimizer_creation() {
616        let optimizer = GraphOptimizer::new();
617        assert!(!optimizer.passes.is_empty());
618    }
619
620    #[test]
621    fn test_constant_folding() {
622        let mut graph = ComputationGraph {
623            operators: vec![
624                GraphOperator {
625                    id: 0,
626                    kernel: KernelType::Custom("Constant".to_string()),
627                    inputs: vec![],
628                    outputs: vec!["const_1".to_string()],
629                    input_shapes: vec![],
630                    output_shape: vec![1],
631                    cache_hints: None,
632                },
633                GraphOperator {
634                    id: 1,
635                    kernel: KernelType::Custom("Add".to_string()),
636                    inputs: vec!["const_1".to_string(), "const_1".to_string()],
637                    outputs: vec!["result".to_string()],
638                    input_shapes: vec![vec![1], vec![1]],
639                    output_shape: vec![1],
640                    cache_hints: None,
641                },
642            ],
643            edges: vec![],
644        };
645
646        let folding = ConstantFolding::new();
647        let result = folding.apply(&mut graph);
648        assert!(result.is_ok());
649    }
650
651    #[test]
652    fn test_dead_code_elimination() {
653        let mut graph = ComputationGraph {
654            operators: vec![
655                GraphOperator {
656                    id: 0,
657                    kernel: KernelType::Linear,
658                    inputs: vec!["input".to_string()],
659                    outputs: vec!["output1".to_string()],
660                    input_shapes: vec![vec![10]],
661                    output_shape: vec![10],
662                    cache_hints: None,
663                },
664                GraphOperator {
665                    id: 1,
666                    kernel: KernelType::Linear,
667                    inputs: vec!["input".to_string()],
668                    outputs: vec!["unused".to_string()], // This output is not used
669                    input_shapes: vec![vec![10]],
670                    output_shape: vec![10],
671                    cache_hints: None,
672                },
673            ],
674            edges: vec![],
675        };
676
677        let dce = DeadCodeElimination::new();
678        let result = dce.apply(&mut graph);
679        assert!(result.is_ok());
680    }
681
682    #[test]
683    fn test_algebraic_simplification() {
684        let mut graph = ComputationGraph {
685            operators: vec![GraphOperator {
686                id: 0,
687                kernel: KernelType::Custom("Add".to_string()),
688                inputs: vec!["x".to_string(), "zero".to_string()],
689                outputs: vec!["result".to_string()],
690                input_shapes: vec![vec![10], vec![10]],
691                output_shape: vec![10],
692                cache_hints: None,
693            }],
694            edges: vec![],
695        };
696
697        let simplify = AlgebraicSimplification::new();
698        let modified = simplify.apply(&mut graph).expect("operation failed in test");
699
700        assert!(modified);
701        assert_eq!(
702            graph.operators[0].kernel,
703            KernelType::Custom("Identity".to_string())
704        );
705    }
706}