tensorlogic-compiler 0.1.0

Compiler for transforming logic expressions into tensor computation graphs
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
//! Strategy mapping utilities.
//!
//! Maps compilation strategies to actual tensor operations.

use anyhow::Result;
use tensorlogic_ir::{EinsumGraph, EinsumNode};

use crate::config::{AndStrategy, NotStrategy, OrStrategy};
use crate::context::CompilerContext;

/// Compile AND operation based on strategy.
pub(crate) fn compile_and_with_strategy(
    left_idx: usize,
    right_idx: usize,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<usize> {
    let result_name = ctx.fresh_temp();
    let result_idx = graph.add_tensor(result_name);

    match ctx.config.and_strategy {
        AndStrategy::Product | AndStrategy::ProductTNorm => {
            // a * b
            let node = EinsumNode::elem_binary("multiply", left_idx, right_idx, result_idx);
            graph.add_node(node)?;
        }
        AndStrategy::Min | AndStrategy::Godel => {
            // min(a, b)
            let node = EinsumNode::elem_binary("min", left_idx, right_idx, result_idx);
            graph.add_node(node)?;
        }
        AndStrategy::ProbabilisticSum => {
            // a + b - a*b
            // First compute a*b
            let mult_name = ctx.fresh_temp();
            let mult_idx = graph.add_tensor(mult_name);
            let mult_node = EinsumNode::elem_binary("multiply", left_idx, right_idx, mult_idx);
            graph.add_node(mult_node)?;

            // Then compute a + b
            let sum_name = ctx.fresh_temp();
            let sum_idx = graph.add_tensor(sum_name);
            let sum_node = EinsumNode::elem_binary("add", left_idx, right_idx, sum_idx);
            graph.add_node(sum_node)?;

            // Finally compute (a + b) - (a*b)
            let node = EinsumNode::elem_binary("subtract", sum_idx, mult_idx, result_idx);
            graph.add_node(node)?;
        }
        AndStrategy::Lukasiewicz => {
            // max(0, a + b - 1)
            // First compute a + b
            let sum_name = ctx.fresh_temp();
            let sum_idx = graph.add_tensor(sum_name);
            let sum_node = EinsumNode::elem_binary("add", left_idx, right_idx, sum_idx);
            graph.add_node(sum_node)?;

            // Create constant 1
            let one_name = "const_1.0".to_string();
            let one_idx = if !graph.tensors.contains(&one_name) {
                graph.add_tensor(one_name)
            } else {
                graph
                    .tensors
                    .iter()
                    .position(|t| t == "const_1.0")
                    .expect("const_1.0 tensor was just registered")
            };

            // Compute (a + b) - 1
            let sub_name = ctx.fresh_temp();
            let sub_idx = graph.add_tensor(sub_name);
            let sub_node = EinsumNode::elem_binary("subtract", sum_idx, one_idx, sub_idx);
            graph.add_node(sub_node)?;

            // Apply ReLU to get max(0, x)
            let node = EinsumNode::elem_unary("relu", sub_idx, result_idx);
            graph.add_node(node)?;
        }
    }

    Ok(result_idx)
}

/// Compile OR operation based on strategy.
pub(crate) fn compile_or_with_strategy(
    left_idx: usize,
    right_idx: usize,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<usize> {
    let result_name = ctx.fresh_temp();
    let result_idx = graph.add_tensor(result_name);

    match ctx.config.or_strategy {
        OrStrategy::Max | OrStrategy::Godel => {
            // max(a, b)
            let node = EinsumNode::elem_binary("max", left_idx, right_idx, result_idx);
            graph.add_node(node)?;
        }
        OrStrategy::ProbabilisticSum | OrStrategy::ProbabilisticSNorm => {
            // a + b - a*b (same as Or_ProbSum operation)
            let node = EinsumNode::elem_binary("or_prob_sum", left_idx, right_idx, result_idx);
            graph.add_node(node)?;
        }
        OrStrategy::Lukasiewicz => {
            // min(1, a + b)
            // First compute a + b
            let sum_name = ctx.fresh_temp();
            let sum_idx = graph.add_tensor(sum_name);
            let sum_node = EinsumNode::elem_binary("add", left_idx, right_idx, sum_idx);
            graph.add_node(sum_node)?;

            // Create constant 1
            let one_name = "const_1.0".to_string();
            let one_idx = if !graph.tensors.contains(&one_name) {
                graph.add_tensor(one_name)
            } else {
                graph
                    .tensors
                    .iter()
                    .position(|t| t == "const_1.0")
                    .expect("const_1.0 tensor was just registered")
            };

            // Compute min(1, a + b)
            let node = EinsumNode::elem_binary("min", one_idx, sum_idx, result_idx);
            graph.add_node(node)?;
        }
    }

    Ok(result_idx)
}

/// Compile NOT operation based on strategy.
pub(crate) fn compile_not_with_strategy(
    input_idx: usize,
    ctx: &mut CompilerContext,
    graph: &mut EinsumGraph,
) -> Result<usize> {
    let result_name = ctx.fresh_temp();
    let result_idx = graph.add_tensor(result_name);

    match ctx.config.not_strategy {
        NotStrategy::Complement => {
            // 1 - a
            let node = EinsumNode::elem_unary("one_minus", input_idx, result_idx);
            graph.add_node(node)?;
        }
        NotStrategy::Sigmoid { temperature } => {
            // 1 / (1 + exp(T * a))
            // Implemented as: sigmoid(-T * a)
            // Since sigmoid(x) = 1/(1+exp(-x)), we have sigmoid(-T*a) = 1/(1+exp(T*a))

            if temperature == 1 {
                // Optimize for T=1: just negate and apply sigmoid
                let neg_name = ctx.fresh_temp();
                let neg_idx = graph.add_tensor(neg_name);
                let neg_node = EinsumNode::elem_unary("negate", input_idx, neg_idx);
                graph.add_node(neg_node)?;

                let node = EinsumNode::elem_unary("sigmoid", neg_idx, result_idx);
                graph.add_node(node)?;
            } else {
                // General case: multiply by temperature, negate, then sigmoid
                // Create constant for temperature
                let temp_f64 = temperature as f64;
                let temp_name = format!("const_{}", temp_f64);
                let temp_idx = if !graph.tensors.contains(&temp_name) {
                    graph.add_tensor(temp_name.clone())
                } else {
                    graph
                        .tensors
                        .iter()
                        .position(|t| t == &temp_name)
                        .expect("temp tensor was just registered")
                };

                // Multiply input by temperature: T * a
                let scaled_name = ctx.fresh_temp();
                let scaled_idx = graph.add_tensor(scaled_name);
                let scale_node =
                    EinsumNode::elem_binary("multiply", temp_idx, input_idx, scaled_idx);
                graph.add_node(scale_node)?;

                // Negate: -(T * a)
                let neg_name = ctx.fresh_temp();
                let neg_idx = graph.add_tensor(neg_name);
                let neg_node = EinsumNode::elem_unary("negate", scaled_idx, neg_idx);
                graph.add_node(neg_node)?;

                // Apply sigmoid: sigmoid(-(T * a)) = 1/(1 + exp(T * a))
                let node = EinsumNode::elem_unary("sigmoid", neg_idx, result_idx);
                graph.add_node(node)?;
            }
        }
    }

    Ok(result_idx)
}

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

    #[test]
    fn test_sigmoid_not_with_temperature_1() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .not_strategy(NotStrategy::Sigmoid { temperature: 1 })
                .build(),
        );
        let mut graph = EinsumGraph::new();

        // Create input tensor
        let input_idx = graph.add_tensor("input");

        // Compile NOT with temperature=1
        let result_idx =
            compile_not_with_strategy(input_idx, &mut ctx, &mut graph).expect("unwrap");

        // Should create: negate -> sigmoid
        assert!(result_idx > input_idx);
        assert_eq!(graph.nodes.len(), 2); // negate + sigmoid

        // First node should be negate
        assert_eq!(graph.nodes[0].operation_description(), "ElemUnary(negate)");
        // Second node should be sigmoid
        assert_eq!(graph.nodes[1].operation_description(), "ElemUnary(sigmoid)");
    }

    #[test]
    fn test_sigmoid_not_with_temperature_2() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .not_strategy(NotStrategy::Sigmoid { temperature: 2 })
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let input_idx = graph.add_tensor("input");

        // Compile NOT with temperature=2
        let result_idx =
            compile_not_with_strategy(input_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > input_idx);
        // Should create: multiply (temp) -> negate -> sigmoid
        assert_eq!(graph.nodes.len(), 3);

        // Check operations in order
        assert_eq!(
            graph.nodes[0].operation_description(),
            "ElemBinary(multiply)"
        );
        assert_eq!(graph.nodes[1].operation_description(), "ElemUnary(negate)");
        assert_eq!(graph.nodes[2].operation_description(), "ElemUnary(sigmoid)");

        // Check that temperature constant was created
        assert!(graph.tensors.contains(&"const_2".to_string()));
    }

    #[test]
    fn test_sigmoid_not_with_temperature_10() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .not_strategy(NotStrategy::Sigmoid { temperature: 10 })
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let input_idx = graph.add_tensor("input");

        let result_idx =
            compile_not_with_strategy(input_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > input_idx);
        assert_eq!(graph.nodes.len(), 3);

        // Check that temperature constant was created
        assert!(graph.tensors.contains(&"const_10".to_string()));
    }

    #[test]
    fn test_complement_not_strategy() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .not_strategy(NotStrategy::Complement)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let input_idx = graph.add_tensor("input");

        let result_idx =
            compile_not_with_strategy(input_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > input_idx);
        assert_eq!(graph.nodes.len(), 1); // Just one_minus
        assert_eq!(
            graph.nodes[0].operation_description(),
            "ElemUnary(one_minus)"
        );
    }

    #[test]
    fn test_and_strategy_product() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .and_strategy(AndStrategy::Product)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let left_idx = graph.add_tensor("left");
        let right_idx = graph.add_tensor("right");

        let result_idx =
            compile_and_with_strategy(left_idx, right_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > right_idx);
        assert_eq!(graph.nodes.len(), 1);
        assert_eq!(
            graph.nodes[0].operation_description(),
            "ElemBinary(multiply)"
        );
    }

    #[test]
    fn test_and_strategy_min() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .and_strategy(AndStrategy::Min)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let left_idx = graph.add_tensor("left");
        let right_idx = graph.add_tensor("right");

        let result_idx =
            compile_and_with_strategy(left_idx, right_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > right_idx);
        assert_eq!(graph.nodes.len(), 1);
        assert_eq!(graph.nodes[0].operation_description(), "ElemBinary(min)");
    }

    #[test]
    fn test_and_strategy_lukasiewicz() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .and_strategy(AndStrategy::Lukasiewicz)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let left_idx = graph.add_tensor("left");
        let right_idx = graph.add_tensor("right");

        let result_idx =
            compile_and_with_strategy(left_idx, right_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > right_idx);
        // add + subtract + relu = 3 operations
        assert_eq!(graph.nodes.len(), 3);
        assert!(graph.tensors.contains(&"const_1.0".to_string()));
    }

    #[test]
    fn test_or_strategy_max() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .or_strategy(OrStrategy::Max)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let left_idx = graph.add_tensor("left");
        let right_idx = graph.add_tensor("right");

        let result_idx =
            compile_or_with_strategy(left_idx, right_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > right_idx);
        assert_eq!(graph.nodes.len(), 1);
        assert_eq!(graph.nodes[0].operation_description(), "ElemBinary(max)");
    }

    #[test]
    fn test_or_strategy_lukasiewicz() {
        let mut ctx = CompilerContext::with_config(
            CompilationConfigBuilder::default()
                .or_strategy(OrStrategy::Lukasiewicz)
                .build(),
        );
        let mut graph = EinsumGraph::new();

        let left_idx = graph.add_tensor("left");
        let right_idx = graph.add_tensor("right");

        let result_idx =
            compile_or_with_strategy(left_idx, right_idx, &mut ctx, &mut graph).expect("unwrap");

        assert!(result_idx > right_idx);
        // add + min = 2 operations
        assert_eq!(graph.nodes.len(), 2);
        assert!(graph.tensors.contains(&"const_1.0".to_string()));
    }
}