arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-core/src/keyswitching/glwe.rs
poulpy-core/src/keyswitching/glwe.rsRaw
  1use poulpy_hal::{
  2    api::{
  3        ModuleN, ScratchAvailable, ScratchTakeBasic, VecZnxBigAddSmallInplace, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes,
  4        VecZnxDftApply, VecZnxDftBytesOf, VecZnxDftCopy, VecZnxIdftApplyConsume, VecZnxNormalize, VecZnxNormalizeTmpBytes,
  5        VmpApplyDftToDft, VmpApplyDftToDftAdd, VmpApplyDftToDftTmpBytes,
  6    },
  7    layouts::{Backend, DataMut, DataViewMut, Module, Scratch, VecZnxBig, VecZnxDft, VecZnxDftToRef, VmpPMat, ZnxInfos},
  8};
  9
 10use crate::{
 11    GLWENormalize, ScratchTakeCore,
 12    layouts::{GGLWEInfos, GGLWEPrepared, GGLWEPreparedToRef, GLWE, GLWEInfos, GLWELayout, GLWEToMut, GLWEToRef, LWEInfos},
 13};
 14
 15impl GLWE<Vec<u8>> {
 16    pub fn keyswitch_tmp_bytes<M, R, A, B, BE: Backend>(module: &M, res_infos: &R, a_infos: &A, key_infos: &B) -> usize
 17    where
 18        R: GLWEInfos,
 19        A: GLWEInfos,
 20        B: GGLWEInfos,
 21        M: GLWEKeyswitch<BE>,
 22    {
 23        module.glwe_keyswitch_tmp_bytes(res_infos, a_infos, key_infos)
 24    }
 25}
 26
 27impl<D: DataMut> GLWE<D> {
 28    pub fn keyswitch<A, B, M, BE: Backend>(&mut self, module: &M, a: &A, b: &B, scratch: &mut Scratch<BE>)
 29    where
 30        A: GLWEToRef,
 31        B: GGLWEPreparedToRef<BE>,
 32        M: GLWEKeyswitch<BE>,
 33        Scratch<BE>: ScratchTakeCore<BE>,
 34    {
 35        module.glwe_keyswitch(self, a, b, scratch);
 36    }
 37
 38    pub fn keyswitch_inplace<A, M, BE: Backend>(&mut self, module: &M, a: &A, scratch: &mut Scratch<BE>)
 39    where
 40        A: GGLWEPreparedToRef<BE>,
 41        M: GLWEKeyswitch<BE>,
 42        Scratch<BE>: ScratchTakeCore<BE>,
 43    {
 44        module.glwe_keyswitch_inplace(self, a, scratch);
 45    }
 46}
 47
 48impl<BE: Backend> GLWEKeyswitch<BE> for Module<BE>
 49where
 50    Self: Sized + GLWEKeySwitchInternal<BE> + VecZnxBigNormalizeTmpBytes + VecZnxBigNormalize<BE> + GLWENormalize<BE>,
 51    Scratch<BE>: ScratchTakeCore<BE>,
 52{
 53    fn glwe_keyswitch_tmp_bytes<R, A, B>(&self, res_infos: &R, a_infos: &A, key_infos: &B) -> usize
 54    where
 55        R: GLWEInfos,
 56        A: GLWEInfos,
 57        B: GGLWEInfos,
 58    {
 59        let cols: usize = res_infos.rank().as_usize() + 1;
 60        let size: usize = if a_infos.base2k() != key_infos.base2k() {
 61            let a_conv_infos = &GLWELayout {
 62                n: a_infos.n(),
 63                base2k: key_infos.base2k(),
 64                k: a_infos.k(),
 65                rank: a_infos.rank(),
 66            };
 67            self.glwe_keyswitch_internal_tmp_bytes(res_infos, a_conv_infos, key_infos) + GLWE::bytes_of_from_infos(a_conv_infos)
 68        } else {
 69            self.glwe_keyswitch_internal_tmp_bytes(res_infos, a_infos, key_infos)
 70        };
 71
 72        size.max(self.vec_znx_big_normalize_tmp_bytes()) + self.bytes_of_vec_znx_dft(cols, key_infos.size())
 73    }
 74
 75    fn glwe_keyswitch<R, A, K>(&self, res: &mut R, a: &A, key: &K, scratch: &mut Scratch<BE>)
 76    where
 77        R: GLWEToMut,
 78        A: GLWEToRef,
 79        K: GGLWEPreparedToRef<BE>,
 80    {
 81        let res: &mut GLWE<&mut [u8]> = &mut res.to_mut();
 82        let a: &GLWE<&[u8]> = &a.to_ref();
 83        let key: &GGLWEPrepared<&[u8], BE> = &key.to_ref();
 84
 85        assert_eq!(
 86            a.rank(),
 87            key.rank_in(),
 88            "a.rank(): {} != b.rank_in(): {}",
 89            a.rank(),
 90            key.rank_in()
 91        );
 92        assert_eq!(
 93            res.rank(),
 94            key.rank_out(),
 95            "res.rank(): {} != b.rank_out(): {}",
 96            res.rank(),
 97            key.rank_out()
 98        );
 99
100        assert_eq!(res.n(), self.n() as u32);
101        assert_eq!(a.n(), self.n() as u32);
102        assert_eq!(key.n(), self.n() as u32);
103
104        let scrach_needed: usize = self.glwe_keyswitch_tmp_bytes(res, a, key);
105
106        assert!(
107            scratch.available() >= scrach_needed,
108            "scratch.available()={} < glwe_keyswitch_tmp_bytes={scrach_needed}",
109            scratch.available(),
110        );
111
112        let base2k_a: usize = a.base2k().into();
113        let base2k_key: usize = key.base2k().into();
114        let base2k_res: usize = res.base2k().into();
115
116        let (res_dft, scratch_1) = scratch.take_vec_znx_dft(self, (res.rank() + 1).into(), key.size()); // Todo optimise
117
118        let res_big: VecZnxBig<&mut [u8], BE> = if base2k_a != base2k_key {
119            let (mut a_conv, scratch_2) = scratch_1.take_glwe(&GLWELayout {
120                n: a.n(),
121                base2k: key.base2k(),
122                k: a.k(),
123                rank: a.rank(),
124            });
125            self.glwe_normalize(&mut a_conv, a, scratch_2);
126            self.glwe_keyswitch_internal(res_dft, &a_conv, key, scratch_2)
127        } else {
128            self.glwe_keyswitch_internal(res_dft, a, key, scratch_1)
129        };
130
131        for i in 0..(res.rank() + 1).into() {
132            self.vec_znx_big_normalize(
133                base2k_res,
134                &mut res.data,
135                i,
136                base2k_key,
137                &res_big,
138                i,
139                scratch_1,
140            );
141        }
142    }
143
144    fn glwe_keyswitch_inplace<R, K>(&self, res: &mut R, key: &K, scratch: &mut Scratch<BE>)
145    where
146        R: GLWEToMut,
147        K: GGLWEPreparedToRef<BE>,
148    {
149        let res: &mut GLWE<&mut [u8]> = &mut res.to_mut();
150        let key: &GGLWEPrepared<&[u8], BE> = &key.to_ref();
151
152        assert_eq!(
153            res.rank(),
154            key.rank_in(),
155            "res.rank(): {} != a.rank_in(): {}",
156            res.rank(),
157            key.rank_in()
158        );
159        assert_eq!(
160            res.rank(),
161            key.rank_out(),
162            "res.rank(): {} != b.rank_out(): {}",
163            res.rank(),
164            key.rank_out()
165        );
166
167        assert_eq!(res.n(), self.n() as u32);
168        assert_eq!(key.n(), self.n() as u32);
169
170        let scrach_needed: usize = self.glwe_keyswitch_tmp_bytes(res, res, key);
171
172        assert!(
173            scratch.available() >= scrach_needed,
174            "scratch.available()={} < glwe_keyswitch_tmp_bytes={scrach_needed}",
175            scratch.available(),
176        );
177
178        let base2k_res: usize = res.base2k().as_usize();
179        let base2k_key: usize = key.base2k().as_usize();
180
181        let (res_dft, scratch_1) = scratch.take_vec_znx_dft(self, (res.rank() + 1).into(), key.size()); // Todo optimise
182
183        let res_big: VecZnxBig<&mut [u8], BE> = if base2k_res != base2k_key {
184            let (mut res_conv, scratch_2) = scratch_1.take_glwe(&GLWELayout {
185                n: res.n(),
186                base2k: key.base2k(),
187                k: res.k(),
188                rank: res.rank(),
189            });
190            self.glwe_normalize(&mut res_conv, res, scratch_2);
191
192            self.glwe_keyswitch_internal(res_dft, &res_conv, key, scratch_2)
193        } else {
194            self.glwe_keyswitch_internal(res_dft, res, key, scratch_1)
195        };
196
197        for i in 0..(res.rank() + 1).into() {
198            self.vec_znx_big_normalize(
199                base2k_res,
200                res.data_mut(),
201                i,
202                base2k_key,
203                &res_big,
204                i,
205                scratch_1,
206            );
207        }
208    }
209}
210
211pub trait GLWEKeyswitch<BE: Backend> {
212    fn glwe_keyswitch_tmp_bytes<R, A, B>(&self, res_infos: &R, a_infos: &A, key_infos: &B) -> usize
213    where
214        R: GLWEInfos,
215        A: GLWEInfos,
216        B: GGLWEInfos;
217
218    fn glwe_keyswitch<R, A, K>(&self, res: &mut R, a: &A, key: &K, scratch: &mut Scratch<BE>)
219    where
220        R: GLWEToMut,
221        A: GLWEToRef,
222        K: GGLWEPreparedToRef<BE>;
223
224    fn glwe_keyswitch_inplace<R, K>(&self, res: &mut R, key: &K, scratch: &mut Scratch<BE>)
225    where
226        R: GLWEToMut,
227        K: GGLWEPreparedToRef<BE>;
228}
229
230impl<BE: Backend> GLWEKeySwitchInternal<BE> for Module<BE> where
231    Self: GGLWEProduct<BE>
232        + VecZnxDftApply<BE>
233        + VecZnxNormalize<BE>
234        + VecZnxIdftApplyConsume<BE>
235        + VecZnxBigAddSmallInplace<BE>
236        + VecZnxNormalizeTmpBytes
237{
238}
239
240pub(crate) trait GLWEKeySwitchInternal<BE: Backend>
241where
242    Self: GGLWEProduct<BE>
243        + VecZnxDftApply<BE>
244        + VecZnxNormalize<BE>
245        + VecZnxIdftApplyConsume<BE>
246        + VecZnxBigAddSmallInplace<BE>
247        + VecZnxNormalizeTmpBytes,
248{
249    fn glwe_keyswitch_internal_tmp_bytes<R, A, K>(&self, res_infos: &R, a_infos: &A, key_infos: &K) -> usize
250    where
251        R: GLWEInfos,
252        A: GLWEInfos,
253        K: GGLWEInfos,
254    {
255        let cols: usize = (a_infos.rank() + 1).into();
256        let a_size: usize = a_infos.size();
257        self.gglwe_product_dft_tmp_bytes(res_infos.size(), a_size, key_infos) + self.bytes_of_vec_znx_dft(cols - 1, a_size)
258    }
259
260    fn glwe_keyswitch_internal<DR, A, K>(
261        &self,
262        mut res: VecZnxDft<DR, BE>,
263        a: &A,
264        key: &K,
265        scratch: &mut Scratch<BE>,
266    ) -> VecZnxBig<DR, BE>
267    where
268        DR: DataMut,
269        A: GLWEToRef,
270        K: GGLWEPreparedToRef<BE>,
271        Scratch<BE>: ScratchTakeCore<BE>,
272    {
273        let a: &GLWE<&[u8]> = &a.to_ref();
274        let key: &GGLWEPrepared<&[u8], BE> = &key.to_ref();
275        assert_eq!(a.base2k(), key.base2k());
276        let cols: usize = (a.rank() + 1).into();
277        let a_size: usize = a.size();
278        let (mut a_dft, scratch_1) = scratch.take_vec_znx_dft(self, cols - 1, a_size);
279        for col_i in 0..cols - 1 {
280            self.vec_znx_dft_apply(1, 0, &mut a_dft, col_i, a.data(), col_i + 1);
281        }
282        self.gglwe_product_dft(&mut res, &a_dft, key, scratch_1);
283        let mut res_big: VecZnxBig<DR, BE> = self.vec_znx_idft_apply_consume(res);
284        self.vec_znx_big_add_small_inplace(&mut res_big, 0, a.data(), 0);
285        res_big
286    }
287}
288
289impl<BE: Backend> GGLWEProduct<BE> for Module<BE> where
290    Self: Sized
291        + ModuleN
292        + VecZnxDftBytesOf
293        + VmpApplyDftToDftTmpBytes
294        + VmpApplyDftToDft<BE>
295        + VmpApplyDftToDftAdd<BE>
296        + VecZnxDftCopy<BE>
297{
298}
299
300pub(crate) trait GGLWEProduct<BE: Backend>
301where
302    Self: Sized
303        + ModuleN
304        + VecZnxDftBytesOf
305        + VmpApplyDftToDftTmpBytes
306        + VmpApplyDftToDft<BE>
307        + VmpApplyDftToDftAdd<BE>
308        + VecZnxDftCopy<BE>,
309{
310    fn gglwe_product_dft_tmp_bytes<K>(&self, res_size: usize, a_size: usize, key_infos: &K) -> usize
311    where
312        K: GGLWEInfos,
313    {
314        let dsize: usize = key_infos.dsize().as_usize();
315
316        if dsize == 1 {
317            self.vmp_apply_dft_to_dft_tmp_bytes(
318                res_size,
319                a_size,
320                key_infos.dnum().into(),
321                (key_infos.rank_in()).into(),
322                (key_infos.rank_out() + 1).into(),
323                key_infos.size(),
324            )
325        } else {
326            let dnum: usize = key_infos.dnum().into();
327            let a_size: usize = a_size.div_ceil(dsize).min(dnum);
328            let ai_dft: usize = self.bytes_of_vec_znx_dft(key_infos.rank_in().into(), a_size);
329
330            let vmp: usize = self.vmp_apply_dft_to_dft_tmp_bytes(
331                res_size,
332                a_size,
333                dnum,
334                (key_infos.rank_in()).into(),
335                (key_infos.rank_out() + 1).into(),
336                key_infos.size(),
337            );
338
339            ai_dft + vmp
340        }
341    }
342
343    fn gglwe_product_dft<DR, A, K>(&self, res: &mut VecZnxDft<DR, BE>, a: &A, key: &K, scratch: &mut Scratch<BE>)
344    where
345        DR: DataMut,
346        A: VecZnxDftToRef<BE>,
347        K: GGLWEPreparedToRef<BE>,
348        Scratch<BE>: ScratchTakeCore<BE>,
349    {
350        let a: &VecZnxDft<&[u8], BE> = &a.to_ref();
351        let key: &GGLWEPrepared<&[u8], BE> = &key.to_ref();
352
353        let cols: usize = a.cols();
354        let a_size: usize = a.size();
355        let pmat: &VmpPMat<&[u8], BE> = &key.data;
356
357        // If dsize == 1, then the digit decomposition is equal to Base2K and we can simply
358        // can the vmp API.
359        if key.dsize() == 1 {
360            self.vmp_apply_dft_to_dft(res, a, pmat, scratch);
361        // If dsize != 1, then the digit decomposition is k * Base2K with k > 1.
362        // As such we need to perform a bivariate polynomial convolution in (X, Y) / (X^{N}+1) with Y = 2^-K
363        // (instead of yn univariate one in X).
364        //
365        // Since the basis in Y is small (in practice degree 6-7 max), we perform it naiveley.
366        // To do so, we group the different limbs of ai_dft by their respective degree in Y
367        // which are multiples of the current digit.
368        // For example if dsize = 3, with ai_dft = [a0, a1, a2, a3, a4, a5, a6],
369        // we group them as [[a0, a3, a5], [a1, a4, a6], [a2, a5, 0]]
370        // and evaluate sum(a_di * pmat * 2^{di*Base2k})
371        } else {
372            let dsize: usize = key.dsize().into();
373            let dnum: usize = key.dnum().into();
374
375            // We bound ai_dft size by the number of rows of the matrix
376            let (mut ai_dft, scratch_1) = scratch.take_vec_znx_dft(self, cols, a_size.div_ceil(dsize).min(dnum));
377            ai_dft.data_mut().fill(0);
378
379            for di in 0..dsize {
380                // Sets ai_dft size according to the current digit (if dsize does not divides a_size),
381                // bounded by the number of rows (digits) in the prepared matrix.
382                ai_dft.set_size(((a_size + di) / dsize).min(dnum));
383
384                // Small optimization for dsize > 2
385                // VMP produce some error e, and since we aggregate vmp * 2^{di * Base2k}, then
386                // we also aggregate ei * 2^{di * Base2k}, with the largest error being ei * 2^{(dsize-1) * Base2k}.
387                // As such we can ignore the last dsize-2 limbs safely of the sum of vmp products.
388                // It is possible to further ignore the last dsize-1 limbs, but this introduce
389                // ~0.5 to 1 bit of additional noise, and thus not chosen here to ensure that the same
390                // noise is kept with respect to the ideal functionality.
391                res.set_size(pmat.size() - ((dsize - di) as isize - 2).max(0) as usize);
392
393                for j in 0..cols {
394                    self.vec_znx_dft_copy(dsize, dsize - di - 1, &mut ai_dft, j, a, j);
395                }
396
397                if di == 0 {
398                    // res = pmat * ai_dft
399                    self.vmp_apply_dft_to_dft(res, &ai_dft, pmat, scratch_1);
400                } else {
401                    // res = (pmat * ai_dft) * 2^{di * Base2k}
402                    self.vmp_apply_dft_to_dft_add(res, &ai_dft, pmat, di, scratch_1);
403                }
404            }
405
406            res.set_size(res.max_size());
407        }
408    }
409}