tasm_lib/array/
inner_product_of_xfes.rs

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
use triton_vm::prelude::*;

use crate::data_type::ArrayType;
use crate::data_type::DataType;
use crate::library::Library;
use crate::traits::basic_snippet::BasicSnippet;

pub struct InnerProductOfXfes {
    pub length: usize,
}

impl InnerProductOfXfes {
    pub fn new(length: usize) -> Self {
        Self { length }
    }

    fn argument_type(&self) -> DataType {
        DataType::Array(Box::new(ArrayType {
            element_type: DataType::Xfe,
            length: self.length,
        }))
    }
}

impl BasicSnippet for InnerProductOfXfes {
    fn inputs(&self) -> Vec<(DataType, String)> {
        vec![
            (self.argument_type(), "*a".to_owned()),
            (self.argument_type(), "*b".to_owned()),
        ]
    }

    fn outputs(&self) -> Vec<(DataType, String)> {
        vec![(DataType::Xfe, "inner_product".to_owned())]
    }

    fn entrypoint(&self) -> String {
        format!("tasmlib_array_inner_product_of_{}_xfes", self.length)
    }

    fn code(&self, _library: &mut Library) -> Vec<LabelledInstruction> {
        let entrypoint = self.entrypoint();

        let accumulate_all_indices = triton_asm![xx_dot_step; self.length];

        triton_asm!(
            {entrypoint}:
                // _ *a *b

                push 0
                push 0
                push 0
                // _ *a *b 0 0 0

                pick 4
                pick 4
                // _ 0 0 0 *a *b

                {&accumulate_all_indices}
                // _ acc2 acc1 acc0 *garbage0 *garbage1

                pop 2
                // _ acc2 acc1 acc0

                return
        )
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use itertools::Itertools;
    use num::Zero;
    use num_traits::ConstZero;
    use rand::prelude::*;
    use triton_vm::twenty_first::math::b_field_element::BFieldElement;
    use triton_vm::twenty_first::math::x_field_element::EXTENSION_DEGREE;

    use super::*;
    use crate::rust_shadowing_helper_functions::array::insert_as_array;
    use crate::rust_shadowing_helper_functions::array::insert_random_array;
    use crate::snippet_bencher::BenchmarkCase;
    use crate::test_helpers::test_rust_equivalence_given_complete_state;
    use crate::traits::function::Function;
    use crate::traits::function::FunctionInitialState;
    use crate::traits::function::ShadowedFunction;
    use crate::traits::rust_shadow::RustShadow;

    impl Function for InnerProductOfXfes {
        fn rust_shadow(
            &self,
            stack: &mut Vec<BFieldElement>,
            memory: &mut HashMap<BFieldElement, BFieldElement>,
        ) {
            fn read_xfe(
                memory: &HashMap<BFieldElement, BFieldElement>,
                address: BFieldElement,
            ) -> XFieldElement {
                let coefficients = [
                    memory.get(&address),
                    memory.get(&(address + bfe!(1))),
                    memory.get(&(address + bfe!(2))),
                ]
                .map(|b| b.copied().unwrap_or(BFieldElement::ZERO));
                xfe!(coefficients)
            }

            let mut array_pointer_b = stack.pop().unwrap();
            let mut array_pointer_a = stack.pop().unwrap();
            let mut acc = XFieldElement::zero();
            for _ in 0..self.length {
                let element_a = read_xfe(memory, array_pointer_a);
                let element_b = read_xfe(memory, array_pointer_b);
                acc += element_a * element_b;
                array_pointer_b += bfe!(3);
                array_pointer_a += bfe!(3);
            }

            for word in acc.coefficients.into_iter().rev() {
                stack.push(word);
            }
        }

        fn pseudorandom_initial_state(
            &self,
            seed: [u8; 32],
            _bench_case: Option<BenchmarkCase>,
        ) -> FunctionInitialState {
            let mut rng: StdRng = SeedableRng::from_seed(seed);
            let array_pointer_a = BFieldElement::new(rng.gen());
            let mut array_pointer_b = BFieldElement::new(rng.gen());
            while array_pointer_a.value().abs_diff(array_pointer_b.value())
                < EXTENSION_DEGREE as u64 * self.length as u64
            {
                array_pointer_b = BFieldElement::new(rng.gen());
            }

            self.prepare_state(array_pointer_a, array_pointer_b)
        }

        fn corner_case_initial_states(&self) -> Vec<FunctionInitialState> {
            let all_zeros = {
                let init_stack = [
                    self.init_stack_for_isolated_run(),
                    vec![BFieldElement::new(0), BFieldElement::new(1 << 40)],
                ]
                .concat();
                FunctionInitialState {
                    stack: init_stack,
                    memory: HashMap::default(),
                }
            };

            vec![all_zeros]
        }
    }

    impl InnerProductOfXfes {
        fn prepare_state(
            &self,
            array_pointer_a: BFieldElement,
            array_pointer_b: BFieldElement,
        ) -> FunctionInitialState {
            let mut memory = HashMap::default();
            insert_random_array(&DataType::Xfe, array_pointer_a, self.length, &mut memory);
            insert_random_array(&DataType::Xfe, array_pointer_b, self.length, &mut memory);

            let mut init_stack = self.init_stack_for_isolated_run();
            init_stack.push(array_pointer_a);
            init_stack.push(array_pointer_b);
            FunctionInitialState {
                stack: init_stack,
                memory,
            }
        }
    }

    #[test]
    fn inner_product_of_xfes_pbt() {
        let snippets = (0..20)
            .chain(100..110)
            .map(|x| InnerProductOfXfes { length: x });
        for test_case in snippets {
            ShadowedFunction::new(test_case).test()
        }
    }

    #[test]
    fn inner_product_unit_test() {
        let a = vec![
            XFieldElement::new([
                BFieldElement::new(3),
                BFieldElement::zero(),
                BFieldElement::zero(),
            ]),
            XFieldElement::new([
                BFieldElement::new(5),
                BFieldElement::zero(),
                BFieldElement::zero(),
            ]),
        ];
        let b = vec![
            XFieldElement::new([
                BFieldElement::new(501),
                BFieldElement::zero(),
                BFieldElement::zero(),
            ]),
            XFieldElement::new([
                BFieldElement::new(1003),
                BFieldElement::zero(),
                BFieldElement::zero(),
            ]),
        ];

        let expected_inner_product = XFieldElement::new([
            BFieldElement::new(3 * 501 + 5 * 1003),
            BFieldElement::zero(),
            BFieldElement::zero(),
        ]);
        assert_eq!(
            expected_inner_product,
            a.iter()
                .cloned()
                .zip(b.iter().cloned())
                .map(|(a, b)| a * b)
                .sum::<XFieldElement>()
        );

        let mut memory = HashMap::default();
        let array_pointer_a = BFieldElement::new(1u64 << 44);
        insert_as_array(array_pointer_a, &mut memory, a);
        let array_pointer_b = BFieldElement::new(1u64 << 45);
        insert_as_array(array_pointer_b, &mut memory, b);

        let snippet = InnerProductOfXfes { length: 2 };
        let expected_final_stack = [
            snippet.init_stack_for_isolated_run(),
            expected_inner_product
                .coefficients
                .into_iter()
                .rev()
                .collect_vec(),
        ]
        .concat();
        let init_stack = [
            snippet.init_stack_for_isolated_run(),
            vec![array_pointer_a, array_pointer_b],
        ]
        .concat();
        test_rust_equivalence_given_complete_state(
            &ShadowedFunction::new(snippet),
            &init_stack,
            &[],
            &NonDeterminism::default().with_ram(memory),
            &None,
            Some(&expected_final_stack),
        );
    }
}

#[cfg(test)]
mod benches {
    use triton_vm::table::master_table::MasterAuxTable;
    use triton_vm::table::master_table::MasterMainTable;
    use triton_vm::table::master_table::MasterTable;

    use super::*;
    use crate::traits::function::ShadowedFunction;
    use crate::traits::rust_shadow::RustShadow;

    #[test]
    fn inner_product_xfes_bench_100() {
        ShadowedFunction::new(InnerProductOfXfes { length: 100 }).bench();
    }

    #[test]
    fn inner_product_xfes_bench_200() {
        ShadowedFunction::new(InnerProductOfXfes { length: 200 }).bench();
    }

    #[test]
    fn inner_product_xfes_bench_num_columns_current_tvm() {
        ShadowedFunction::new(InnerProductOfXfes {
            length: MasterMainTable::NUM_COLUMNS + MasterAuxTable::NUM_COLUMNS,
        })
        .bench();
    }

    #[test]
    fn inner_product_xfes_bench_num_constraints_current_tvm() {
        ShadowedFunction::new(InnerProductOfXfes {
            length: MasterAuxTable::NUM_CONSTRAINTS,
        })
        .bench();
    }
}