poulpy/base2k/src/mat_znx_dft_ops.rs
base2k/src/mat_znx_dft_ops.rsRaw
1use crate::ffi::vec_znx_dft::vec_znx_dft_t;
2use crate::ffi::vmp;
3use crate::znx_base::{ZnxInfos, ZnxView, ZnxViewMut};
4use crate::{
5 Backend, FFT64, MatZnxDft, MatZnxDftOwned, MatZnxDftToMut, MatZnxDftToRef, Module, Scratch, VecZnxDft, VecZnxDftToMut,
6 VecZnxDftToRef,
7};
8
9pub trait MatZnxDftAlloc<B: Backend> {
10 /// Allocates a new [MatZnxDft] with the given number of rows and columns.
11 ///
12 /// # Arguments
13 ///
14 /// * `rows`: number of rows (number of [VecZnxDft]).
15 /// * `size`: number of size (number of size of each [VecZnxDft]).
16 fn new_mat_znx_dft(&self, rows: usize, cols_in: usize, cols_out: usize, size: usize) -> MatZnxDftOwned<B>;
17
18 fn bytes_of_mat_znx_dft(&self, rows: usize, cols_in: usize, cols_out: usize, size: usize) -> usize;
19
20 fn new_mat_znx_dft_from_bytes(
21 &self,
22 rows: usize,
23 cols_in: usize,
24 cols_out: usize,
25 size: usize,
26 bytes: Vec<u8>,
27 ) -> MatZnxDftOwned<B>;
28}
29
30pub trait MatZnxDftScratch {
31 /// Returns the size of the stratch space necessary for [MatZnxDftOps::vmp_apply_dft_to_dft].
32 fn vmp_apply_tmp_bytes(
33 &self,
34 res_size: usize,
35 a_size: usize,
36 b_rows: usize,
37 b_cols_in: usize,
38 b_cols_out: usize,
39 b_size: usize,
40 ) -> usize;
41}
42
43/// This trait implements methods for vector matrix product,
44/// that is, multiplying a [VecZnx] with a [MatZnxDft].
45pub trait MatZnxDftOps<BACKEND: Backend> {
46 /// Prepares the ith-row of [MatZnxDft] from a [VecZnxDft].
47 ///
48 /// # Arguments
49 ///
50 /// * `b`: [MatZnxDft] on which the values are encoded.
51 /// * `a`: the [VecZnxDft] to encode on the [MatZnxDft].
52 /// * `row_i`: the index of the row to prepare.
53 ///
54 /// The size of buf can be obtained with [MatZnxDftOps::vmp_prepare_tmp_bytes].
55 fn vmp_prepare_row<R, A>(&self, res: &mut R, res_row: usize, res_col_in: usize, a: &A)
56 where
57 R: MatZnxDftToMut<BACKEND>,
58 A: VecZnxDftToRef<BACKEND>;
59
60 /// Extracts the ith-row of [MatZnxDft] into a [VecZnxDft].
61 ///
62 /// # Arguments
63 ///
64 /// * `b`: the [VecZnxDft] to on which to extract the row of the [MatZnxDft].
65 /// * `a`: [MatZnxDft] on which the values are encoded.
66 /// * `row_i`: the index of the row to extract.
67 fn vmp_extract_row<R, A>(&self, res: &mut R, a: &A, a_row: usize, a_col_in: usize)
68 where
69 R: VecZnxDftToMut<BACKEND>,
70 A: MatZnxDftToRef<BACKEND>;
71
72 /// Applies the vector matrix product [VecZnxDft] x [MatZnxDft].
73 /// The size of `buf` is given by [MatZnxDftOps::vmp_apply_dft_to_dft_tmp_bytes].
74 ///
75 /// A vector matrix product is equivalent to a sum of [crate::SvpPPolOps::svp_apply_dft]
76 /// where each [crate::Scalar] is a limb of the input [VecZnxDft] (equivalent to an [crate::SvpPPol])
77 /// and each vector a [VecZnxDft] (row) of the [MatZnxDft].
78 ///
79 /// As such, given an input [VecZnx] of `i` size and a [MatZnxDft] of `i` rows and
80 /// `j` size, the output is a [VecZnx] of `j` size.
81 ///
82 /// If there is a mismatch between the dimensions the largest valid ones are used.
83 ///
84 /// ```text
85 /// |a b c d| x |e f g| = (a * |e f g| + b * |h i j| + c * |k l m|) = |n o p|
86 /// |h i j|
87 /// |k l m|
88 /// ```
89 /// where each element is a [VecZnxDft].
90 ///
91 /// # Arguments
92 ///
93 /// * `c`: the output of the vector matrix product, as a [VecZnxDft].
94 /// * `a`: the left operand [VecZnxDft] of the vector matrix product.
95 /// * `b`: the right operand [MatZnxDft] of the vector matrix product.
96 /// * `buf`: scratch space, the size can be obtained with [MatZnxDftOps::vmp_apply_dft_to_dft_tmp_bytes].
97 fn vmp_apply<R, A, B>(&self, res: &mut R, a: &A, b: &B, scratch: &mut Scratch)
98 where
99 R: VecZnxDftToMut<BACKEND>,
100 A: VecZnxDftToRef<BACKEND>,
101 B: MatZnxDftToRef<BACKEND>;
102
103 // Same as [MatZnxDftOps::vmp_apply] except result is added on R instead of overwritting R.
104 fn vmp_apply_add<R, A, B>(&self, res: &mut R, a: &A, b: &B, scratch: &mut Scratch)
105 where
106 R: VecZnxDftToMut<BACKEND>,
107 A: VecZnxDftToRef<BACKEND>,
108 B: MatZnxDftToRef<BACKEND>;
109}
110
111impl<B: Backend> MatZnxDftAlloc<B> for Module<B> {
112 fn bytes_of_mat_znx_dft(&self, rows: usize, cols_in: usize, cols_out: usize, size: usize) -> usize {
113 MatZnxDftOwned::bytes_of(self, rows, cols_in, cols_out, size)
114 }
115
116 fn new_mat_znx_dft(&self, rows: usize, cols_in: usize, cols_out: usize, size: usize) -> MatZnxDftOwned<B> {
117 MatZnxDftOwned::new(self, rows, cols_in, cols_out, size)
118 }
119
120 fn new_mat_znx_dft_from_bytes(
121 &self,
122 rows: usize,
123 cols_in: usize,
124 cols_out: usize,
125 size: usize,
126 bytes: Vec<u8>,
127 ) -> MatZnxDftOwned<B> {
128 MatZnxDftOwned::new_from_bytes(self, rows, cols_in, cols_out, size, bytes)
129 }
130}
131
132impl<BACKEND: Backend> MatZnxDftScratch for Module<BACKEND> {
133 fn vmp_apply_tmp_bytes(
134 &self,
135 res_size: usize,
136 a_size: usize,
137 b_rows: usize,
138 b_cols_in: usize,
139 b_cols_out: usize,
140 b_size: usize,
141 ) -> usize {
142 unsafe {
143 vmp::vmp_apply_dft_to_dft_tmp_bytes(
144 self.ptr,
145 (res_size * b_cols_out) as u64,
146 (a_size * b_cols_in) as u64,
147 (b_rows * b_cols_in) as u64,
148 (b_size * b_cols_out) as u64,
149 ) as usize
150 }
151 }
152}
153
154impl MatZnxDftOps<FFT64> for Module<FFT64> {
155 fn vmp_prepare_row<R, A>(&self, res: &mut R, res_row: usize, res_col_in: usize, a: &A)
156 where
157 R: MatZnxDftToMut<FFT64>,
158 A: VecZnxDftToRef<FFT64>,
159 {
160 let mut res: MatZnxDft<&mut [u8], _> = res.to_mut();
161 let a: VecZnxDft<&[u8], _> = a.to_ref();
162
163 #[cfg(debug_assertions)]
164 {
165 assert_eq!(res.n(), self.n());
166 assert_eq!(a.n(), self.n());
167 assert_eq!(
168 a.cols(),
169 res.cols_out(),
170 "a.cols(): {} != res.cols_out(): {}",
171 a.cols(),
172 res.cols_out()
173 );
174 assert!(
175 res_row < res.rows(),
176 "res_row: {} >= res.rows(): {}",
177 res_row,
178 res.rows()
179 );
180 assert!(
181 res_col_in < res.cols_in(),
182 "res_col_in: {} >= res.cols_in(): {}",
183 res_col_in,
184 res.cols_in()
185 );
186 assert_eq!(
187 res.size(),
188 a.size(),
189 "res.size(): {} != a.size(): {}",
190 res.size(),
191 a.size()
192 );
193 }
194
195 unsafe {
196 vmp::vmp_prepare_row_dft(
197 self.ptr,
198 res.as_mut_ptr() as *mut vmp::vmp_pmat_t,
199 a.as_ptr() as *const vec_znx_dft_t,
200 (res_row * res.cols_in() + res_col_in) as u64,
201 (res.rows() * res.cols_in()) as u64,
202 (res.size() * res.cols_out()) as u64,
203 );
204 }
205 }
206
207 fn vmp_extract_row<R, A>(&self, res: &mut R, a: &A, a_row: usize, a_col_in: usize)
208 where
209 R: VecZnxDftToMut<FFT64>,
210 A: MatZnxDftToRef<FFT64>,
211 {
212 let mut res: VecZnxDft<&mut [u8], _> = res.to_mut();
213 let a: MatZnxDft<&[u8], _> = a.to_ref();
214
215 #[cfg(debug_assertions)]
216 {
217 assert_eq!(res.n(), self.n());
218 assert_eq!(a.n(), self.n());
219 assert_eq!(
220 res.cols(),
221 a.cols_out(),
222 "res.cols(): {} != a.cols_out(): {}",
223 res.cols(),
224 a.cols_out()
225 );
226 assert!(
227 a_row < a.rows(),
228 "a_row: {} >= a.rows(): {}",
229 a_row,
230 a.rows()
231 );
232 assert!(
233 a_col_in < a.cols_in(),
234 "a_col_in: {} >= a.cols_in(): {}",
235 a_col_in,
236 a.cols_in()
237 );
238 assert_eq!(
239 res.size(),
240 a.size(),
241 "res.size(): {} != a.size(): {}",
242 res.size(),
243 a.size()
244 );
245 }
246 unsafe {
247 vmp::vmp_extract_row_dft(
248 self.ptr,
249 res.as_mut_ptr() as *mut vec_znx_dft_t,
250 a.as_ptr() as *const vmp::vmp_pmat_t,
251 (a_row * a.cols_in() + a_col_in) as u64,
252 (a.rows() * a.cols_in()) as u64,
253 (a.size() * a.cols_out()) as u64,
254 );
255 }
256 }
257
258 fn vmp_apply<R, A, B>(&self, res: &mut R, a: &A, b: &B, scratch: &mut Scratch)
259 where
260 R: VecZnxDftToMut<FFT64>,
261 A: VecZnxDftToRef<FFT64>,
262 B: MatZnxDftToRef<FFT64>,
263 {
264 let mut res: VecZnxDft<&mut [u8], _> = res.to_mut();
265 let a: VecZnxDft<&[u8], _> = a.to_ref();
266 let b: MatZnxDft<&[u8], _> = b.to_ref();
267
268 #[cfg(debug_assertions)]
269 {
270 assert_eq!(res.n(), self.n());
271 assert_eq!(b.n(), self.n());
272 assert_eq!(a.n(), self.n());
273 assert_eq!(
274 res.cols(),
275 b.cols_out(),
276 "res.cols(): {} != b.cols_out: {}",
277 res.cols(),
278 b.cols_out()
279 );
280 assert_eq!(
281 a.cols(),
282 b.cols_in(),
283 "a.cols(): {} != b.cols_in: {}",
284 a.cols(),
285 b.cols_in()
286 );
287 }
288
289 let (tmp_bytes, _) = scratch.tmp_slice(self.vmp_apply_tmp_bytes(
290 res.size(),
291 a.size(),
292 b.rows(),
293 b.cols_in(),
294 b.cols_out(),
295 b.size(),
296 ));
297 unsafe {
298 vmp::vmp_apply_dft_to_dft(
299 self.ptr,
300 res.as_mut_ptr() as *mut vec_znx_dft_t,
301 (res.size() * res.cols()) as u64,
302 a.as_ptr() as *const vec_znx_dft_t,
303 (a.size() * a.cols()) as u64,
304 b.as_ptr() as *const vmp::vmp_pmat_t,
305 (b.rows() * b.cols_in()) as u64,
306 (b.size() * b.cols_out()) as u64,
307 tmp_bytes.as_mut_ptr(),
308 )
309 }
310 }
311
312 fn vmp_apply_add<R, A, B>(&self, res: &mut R, a: &A, b: &B, scratch: &mut Scratch)
313 where
314 R: VecZnxDftToMut<FFT64>,
315 A: VecZnxDftToRef<FFT64>,
316 B: MatZnxDftToRef<FFT64> {
317 let mut res: VecZnxDft<&mut [u8], _> = res.to_mut();
318 let a: VecZnxDft<&[u8], _> = a.to_ref();
319 let b: MatZnxDft<&[u8], _> = b.to_ref();
320
321 #[cfg(debug_assertions)]
322 {
323 assert_eq!(res.n(), self.n());
324 assert_eq!(b.n(), self.n());
325 assert_eq!(a.n(), self.n());
326 assert_eq!(
327 res.cols(),
328 b.cols_out(),
329 "res.cols(): {} != b.cols_out: {}",
330 res.cols(),
331 b.cols_out()
332 );
333 assert_eq!(
334 a.cols(),
335 b.cols_in(),
336 "a.cols(): {} != b.cols_in: {}",
337 a.cols(),
338 b.cols_in()
339 );
340 }
341
342 let (tmp_bytes, _) = scratch.tmp_slice(self.vmp_apply_tmp_bytes(
343 res.size(),
344 a.size(),
345 b.rows(),
346 b.cols_in(),
347 b.cols_out(),
348 b.size(),
349 ));
350 unsafe {
351 vmp::vmp_apply_dft_to_dft_add(
352 self.ptr,
353 res.as_mut_ptr() as *mut vec_znx_dft_t,
354 (res.size() * res.cols()) as u64,
355 a.as_ptr() as *const vec_znx_dft_t,
356 (a.size() * a.cols()) as u64,
357 b.as_ptr() as *const vmp::vmp_pmat_t,
358 (b.rows() * b.cols_in()) as u64,
359 (b.size() * b.cols_out()) as u64,
360 tmp_bytes.as_mut_ptr(),
361 )
362 }
363 }
364}
365#[cfg(test)]
366mod tests {
367 use crate::{
368 Decoding, FFT64, FillUniform, MatZnxDft, MatZnxDftOps, Module, ScratchOwned, VecZnx, VecZnxAlloc, VecZnxBig,
369 VecZnxBigAlloc, VecZnxBigOps, VecZnxBigScratch, VecZnxDft, VecZnxDftAlloc, VecZnxDftOps, ZnxInfos, ZnxView, ZnxViewMut,
370 };
371 use sampling::source::Source;
372
373 use super::{MatZnxDftAlloc, MatZnxDftScratch};
374
375 #[test]
376 fn vmp_prepare_row() {
377 let module: Module<FFT64> = Module::<FFT64>::new(16);
378 let log_base2k: usize = 8;
379 let mat_rows: usize = 4;
380 let mat_cols_in: usize = 2;
381 let mat_cols_out: usize = 2;
382 let mat_size: usize = 5;
383 let mut a: VecZnx<Vec<u8>> = module.new_vec_znx(mat_cols_out, mat_size);
384 let mut a_dft: VecZnxDft<Vec<u8>, FFT64> = module.new_vec_znx_dft(mat_cols_out, mat_size);
385 let mut b_dft: VecZnxDft<Vec<u8>, FFT64> = module.new_vec_znx_dft(mat_cols_out, mat_size);
386 let mut mat: MatZnxDft<Vec<u8>, FFT64> = module.new_mat_znx_dft(mat_rows, mat_cols_in, mat_cols_out, mat_size);
387
388 for col_in in 0..mat_cols_in {
389 for row_i in 0..mat_rows {
390 let mut source: Source = Source::new([0u8; 32]);
391 (0..mat_cols_out).for_each(|col_out| {
392 a.fill_uniform(log_base2k, col_out, mat_size, &mut source);
393 module.vec_znx_dft(&mut a_dft, col_out, &a, col_out);
394 });
395 module.vmp_prepare_row(&mut mat, row_i, col_in, &a_dft);
396 module.vmp_extract_row(&mut b_dft, &mat, row_i, col_in);
397 assert_eq!(a_dft.raw(), b_dft.raw());
398 }
399 }
400 }
401
402 #[test]
403 fn vmp_apply() {
404 let log_n: i32 = 5;
405 let n: usize = 1 << log_n;
406
407 let module: Module<FFT64> = Module::<FFT64>::new(n);
408 let log_base2k: usize = 15;
409 let a_size: usize = 5;
410 let mat_size: usize = 6;
411 let res_size: usize = 5;
412
413 [1, 2].iter().for_each(|in_cols| {
414 [1, 2].iter().for_each(|out_cols| {
415 let a_cols: usize = *in_cols;
416 let res_cols: usize = *out_cols;
417
418 let mat_rows: usize = a_size;
419 let mat_cols_in: usize = a_cols;
420 let mat_cols_out: usize = res_cols;
421 let res_cols: usize = mat_cols_out;
422
423 let mut scratch: ScratchOwned = ScratchOwned::new(
424 module.vmp_apply_tmp_bytes(
425 res_size,
426 a_size,
427 mat_rows,
428 mat_cols_in,
429 mat_cols_out,
430 mat_size,
431 ) | module.vec_znx_big_normalize_tmp_bytes(),
432 );
433
434 let mut a: VecZnx<Vec<u8>> = module.new_vec_znx(a_cols, a_size);
435
436 (0..a_cols).for_each(|i| {
437 a.at_mut(i, 2)[i + 1] = 1;
438 });
439
440 let mut mat_znx_dft: MatZnxDft<Vec<u8>, FFT64> =
441 module.new_mat_znx_dft(mat_rows, mat_cols_in, mat_cols_out, mat_size);
442
443 let mut c_dft: VecZnxDft<Vec<u8>, FFT64> = module.new_vec_znx_dft(mat_cols_out, mat_size);
444 let mut c_big: VecZnxBig<Vec<u8>, FFT64> = module.new_vec_znx_big(mat_cols_out, mat_size);
445
446 let mut tmp: VecZnx<Vec<u8>> = module.new_vec_znx(mat_cols_out, mat_size);
447
448 // Construts a [VecZnxMatDft] that performs cyclic rotations on each submatrix.
449 (0..a.size()).for_each(|row_i| {
450 (0..mat_cols_in).for_each(|col_in_i| {
451 (0..mat_cols_out).for_each(|col_out_i| {
452 let idx = 1 + col_in_i * mat_cols_out + col_out_i;
453 tmp.at_mut(col_out_i, row_i)[idx] = 1 as i64; // X^{idx}
454 module.vec_znx_dft(&mut c_dft, col_out_i, &tmp, col_out_i);
455 tmp.at_mut(col_out_i, row_i)[idx] = 0 as i64;
456 });
457 module.vmp_prepare_row(&mut mat_znx_dft, row_i, col_in_i, &c_dft);
458 });
459 });
460
461 let mut a_dft: VecZnxDft<Vec<u8>, FFT64> = module.new_vec_znx_dft(a_cols, a_size);
462 (0..a_cols).for_each(|i| {
463 module.vec_znx_dft(&mut a_dft, i, &a, i);
464 });
465
466 module.vmp_apply(&mut c_dft, &a_dft, &mat_znx_dft, scratch.borrow());
467
468 let mut res_have_vi64: Vec<i64> = vec![i64::default(); n];
469
470 let mut res_have: VecZnx<Vec<u8>> = module.new_vec_znx(res_cols, res_size);
471 (0..mat_cols_out).for_each(|i| {
472 module.vec_znx_idft_tmp_a(&mut c_big, i, &mut c_dft, i);
473 module.vec_znx_big_normalize(log_base2k, &mut res_have, i, &c_big, i, scratch.borrow());
474 });
475
476 (0..mat_cols_out).for_each(|col_i| {
477 let mut res_want_vi64: Vec<i64> = vec![i64::default(); n];
478 (0..a_cols).for_each(|i| {
479 res_want_vi64[(i + 1) + (1 + i * mat_cols_out + col_i)] = 1;
480 });
481 res_have.decode_vec_i64(col_i, log_base2k, log_base2k * 3, &mut res_have_vi64);
482 assert_eq!(res_have_vi64, res_want_vi64);
483 });
484 });
485 });
486 }
487}