arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-core/src/conversion/gglwe_to_ggsw.rs
poulpy-core/src/conversion/gglwe_to_ggsw.rsRaw
  1use poulpy_hal::{
  2    api::{
  3        ModuleN, ScratchAvailable, ScratchTakeBasic, VecZnxBigBytesOf, VecZnxBigNormalize, VecZnxCopy, VecZnxDftAddInplace,
  4        VecZnxDftApply, VecZnxDftBytesOf, VecZnxDftCopy, VecZnxIdftApplyTmpA, VecZnxNormalize, VecZnxNormalizeTmpBytes,
  5        VmpApplyDftToDft, VmpApplyDftToDftAdd, VmpApplyDftToDftTmpBytes,
  6    },
  7    layouts::{Backend, DataMut, Module, Scratch, VmpPMat, ZnxInfos},
  8};
  9
 10use crate::{
 11    ScratchTakeCore,
 12    layouts::{
 13        GGLWE, GGLWEInfos, GGLWEToRef, GGSW, GGSWInfos, GGSWToMut, GLWEInfos, LWEInfos,
 14        prepared::{TensorKeyPrepared, TensorKeyPreparedToRef},
 15    },
 16    operations::GLWEOperations,
 17};
 18
 19impl GGLWE<Vec<u8>> {
 20    pub fn from_gglw_tmp_bytes<R, A, M, BE: Backend>(module: &M, res_infos: &R, tsk_infos: &A) -> usize
 21    where
 22        M: GGSWFromGGLWE<BE>,
 23        R: GGSWInfos,
 24        A: GGLWEInfos,
 25    {
 26        module.ggsw_from_gglwe_tmp_bytes(res_infos, tsk_infos)
 27    }
 28}
 29
 30impl<D: DataMut> GGSW<D> {
 31    pub fn from_gglwe<G, M, T, BE: Backend>(&mut self, module: &M, gglwe: &G, tsk: &T, scratch: &mut Scratch<BE>)
 32    where
 33        M: GGSWFromGGLWE<BE>,
 34        G: GGLWEToRef,
 35        T: TensorKeyPreparedToRef<BE>,
 36        Scratch<BE>: ScratchTakeCore<BE>,
 37    {
 38        module.ggsw_from_gglwe(self, gglwe, tsk, scratch);
 39    }
 40}
 41
 42impl<BE: Backend> GGSWFromGGLWE<BE> for Module<BE> where Self: GGSWExpandRows<BE> + VecZnxCopy {}
 43
 44pub trait GGSWFromGGLWE<BE: Backend>
 45where
 46    Self: GGSWExpandRows<BE> + VecZnxCopy,
 47{
 48    fn ggsw_from_gglwe_tmp_bytes<R, A>(&self, res_infos: &R, tsk_infos: &A) -> usize
 49    where
 50        R: GGSWInfos,
 51        A: GGLWEInfos,
 52    {
 53        self.ggsw_expand_rows_tmp_bytes(res_infos, tsk_infos)
 54    }
 55
 56    fn ggsw_from_gglwe<R, A, T>(&self, res: &mut R, a: &A, tsk: &T, scratch: &mut Scratch<BE>)
 57    where
 58        R: GGSWToMut,
 59        A: GGLWEToRef,
 60        T: TensorKeyPreparedToRef<BE>,
 61        Scratch<BE>: ScratchTakeCore<BE>,
 62    {
 63        let res: &mut GGSW<&mut [u8]> = &mut res.to_mut();
 64        let a: &GGLWE<&[u8]> = &a.to_ref();
 65        let tsk: &TensorKeyPrepared<&[u8], BE> = &tsk.to_ref();
 66
 67        assert_eq!(res.rank(), a.rank_out());
 68        assert_eq!(res.dnum(), a.dnum());
 69        assert_eq!(res.n(), self.n() as u32);
 70        assert_eq!(a.n(), self.n() as u32);
 71        assert_eq!(tsk.n(), self.n() as u32);
 72
 73        for row in 0..res.dnum().into() {
 74            res.at_mut(row, 0).copy(self, &a.at(row, 0));
 75        }
 76
 77        self.ggsw_expand_row(res, tsk, scratch);
 78    }
 79}
 80
 81impl<BE: Backend> GGSWExpandRows<BE> for Module<BE> where
 82    Self: Sized
 83        + ModuleN
 84        + VecZnxDftBytesOf
 85        + VmpApplyDftToDftTmpBytes
 86        + VecZnxBigBytesOf
 87        + VecZnxNormalizeTmpBytes
 88        + VecZnxDftBytesOf
 89        + VmpApplyDftToDftTmpBytes
 90        + VecZnxBigBytesOf
 91        + VecZnxNormalizeTmpBytes
 92        + VecZnxDftApply<BE>
 93        + VecZnxDftCopy<BE>
 94        + VmpApplyDftToDft<BE>
 95        + VmpApplyDftToDftAdd<BE>
 96        + VecZnxDftAddInplace<BE>
 97        + VecZnxBigNormalize<BE>
 98        + VecZnxIdftApplyTmpA<BE>
 99        + VecZnxNormalize<BE>
100{
101}
102
103pub(crate) trait GGSWExpandRows<BE: Backend>
104where
105    Self: Sized
106        + ModuleN
107        + VecZnxDftBytesOf
108        + VmpApplyDftToDftTmpBytes
109        + VecZnxBigBytesOf
110        + VecZnxNormalizeTmpBytes
111        + VecZnxDftBytesOf
112        + VmpApplyDftToDftTmpBytes
113        + VecZnxBigBytesOf
114        + VecZnxNormalizeTmpBytes
115        + VecZnxDftApply<BE>
116        + VecZnxDftCopy<BE>
117        + VmpApplyDftToDft<BE>
118        + VmpApplyDftToDftAdd<BE>
119        + VecZnxDftAddInplace<BE>
120        + VecZnxBigNormalize<BE>
121        + VecZnxIdftApplyTmpA<BE>
122        + VecZnxNormalize<BE>,
123{
124    fn ggsw_expand_rows_tmp_bytes<R, A>(&self, res_infos: &R, tsk_infos: &A) -> usize
125    where
126        R: GGSWInfos,
127        A: GGLWEInfos,
128    {
129        let tsk_size: usize = tsk_infos.k().div_ceil(tsk_infos.base2k()) as usize;
130        let size_in: usize = res_infos
131            .k()
132            .div_ceil(tsk_infos.base2k())
133            .div_ceil(tsk_infos.dsize().into()) as usize;
134
135        let tmp_dft_i: usize = self.bytes_of_vec_znx_dft((tsk_infos.rank_out() + 1).into(), tsk_size);
136        let tmp_a: usize = self.bytes_of_vec_znx_dft(1, size_in);
137        let vmp: usize = self.vmp_apply_dft_to_dft_tmp_bytes(
138            tsk_size,
139            size_in,
140            size_in,
141            (tsk_infos.rank_in()).into(),  // Verify if rank+1
142            (tsk_infos.rank_out()).into(), // Verify if rank+1
143            tsk_size,
144        );
145        let tmp_idft: usize = self.bytes_of_vec_znx_big(1, tsk_size);
146        let norm: usize = self.vec_znx_normalize_tmp_bytes();
147
148        tmp_dft_i + ((tmp_a + vmp) | (tmp_idft + norm))
149    }
150
151    fn ggsw_expand_row<R, T>(&self, res: &mut R, tsk: &T, scratch: &mut Scratch<BE>)
152    where
153        R: GGSWToMut,
154        T: TensorKeyPreparedToRef<BE>,
155        Scratch<BE>: ScratchTakeCore<BE>,
156    {
157        let res: &mut GGSW<&mut [u8]> = &mut res.to_mut();
158        let tsk: &TensorKeyPrepared<&[u8], BE> = &tsk.to_ref();
159
160        let basek_in: usize = res.base2k().into();
161        let basek_tsk: usize = tsk.base2k().into();
162
163        assert!(scratch.available() >= self.ggsw_expand_rows_tmp_bytes(res, tsk));
164
165        let rank: usize = res.rank().into();
166        let cols: usize = rank + 1;
167
168        let a_size: usize = (res.size() * basek_in).div_ceil(basek_tsk);
169
170        // Keyswitch the j-th row of the col 0
171        for row_i in 0..res.dnum().into() {
172            let a = &res.at(row_i, 0).data;
173
174            // Pre-compute DFT of (a0, a1, a2)
175            let (mut ci_dft, scratch_1) = scratch.take_vec_znx_dft(self, cols, a_size);
176
177            if basek_in == basek_tsk {
178                for i in 0..cols {
179                    self.vec_znx_dft_apply(1, 0, &mut ci_dft, i, a, i);
180                }
181            } else {
182                let (mut a_conv, scratch_2) = scratch_1.take_vec_znx(self, 1, a_size);
183                for i in 0..cols {
184                    self.vec_znx_normalize(basek_tsk, &mut a_conv, 0, basek_in, a, i, scratch_2);
185                    self.vec_znx_dft_apply(1, 0, &mut ci_dft, i, &a_conv, 0);
186                }
187            }
188
189            for col_j in 1..cols {
190                // Example for rank 3:
191                //
192                // Note: M is a vector (m, Bm, B^2m, B^3m, ...), so each column is
193                // actually composed of that many dnum and we focus on a specific row here
194                // implicitely given ci_dft.
195                //
196                // # Input
197                //
198                // col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0    , a1    , a2    )
199                // col 1: (0, 0, 0, 0)
200                // col 2: (0, 0, 0, 0)
201                // col 3: (0, 0, 0, 0)
202                //
203                // # Output
204                //
205                // col 0: (-(a0s0 + a1s1 + a2s2) + M[i], a0       , a1       , a2       )
206                // col 1: (-(b0s0 + b1s1 + b2s2)       , b0 + M[i], b1       , b2       )
207                // col 2: (-(c0s0 + c1s1 + c2s2)       , c0       , c1 + M[i], c2       )
208                // col 3: (-(d0s0 + d1s1 + d2s2)       , d0       , d1       , d2 + M[i])
209
210                let dsize: usize = tsk.dsize().into();
211
212                let (mut tmp_dft_i, scratch_2) = scratch_1.take_vec_znx_dft(self, cols, tsk.size());
213                let (mut tmp_a, scratch_3) = scratch_2.take_vec_znx_dft(self, 1, ci_dft.size().div_ceil(dsize));
214
215                {
216                    // Performs a key-switch for each combination of s[i]*s[j], i.e. for a0, a1, a2
217                    //
218                    // # Example for col=1
219                    //
220                    // a0 * (-(f0s0 + f1s1 + f1s2) + s0^2, f0, f1, f2) = (-(a0f0s0 + a0f1s1 + a0f1s2) + a0s0^2, a0f0, a0f1, a0f2)
221                    // +
222                    // a1 * (-(g0s0 + g1s1 + g1s2) + s0s1, g0, g1, g2) = (-(a1g0s0 + a1g1s1 + a1g1s2) + a1s0s1, a1g0, a1g1, a1g2)
223                    // +
224                    // a2 * (-(h0s0 + h1s1 + h1s2) + s0s2, h0, h1, h2) = (-(a2h0s0 + a2h1s1 + a2h1s2) + a2s0s2, a2h0, a2h1, a2h2)
225                    // =
226                    // (-(x0s0 + x1s1 + x2s2) + s0(a0s0 + a1s1 + a2s2), x0, x1, x2)
227                    for col_i in 1..cols {
228                        let pmat: &VmpPMat<&[u8], BE> = &tsk.at(col_i - 1, col_j - 1).key.data; // Selects Enc(s[i]s[j])
229
230                        // Extracts a[i] and multipies with Enc(s[i]s[j])
231                        for di in 0..dsize {
232                            tmp_a.set_size((ci_dft.size() + di) / dsize);
233
234                            // Small optimization for dsize > 2
235                            // VMP produce some error e, and since we aggregate vmp * 2^{di * B}, then
236                            // we also aggregate ei * 2^{di * B}, with the largest error being ei * 2^{(dsize-1) * B}.
237                            // As such we can ignore the last dsize-2 limbs safely of the sum of vmp products.
238                            // It is possible to further ignore the last dsize-1 limbs, but this introduce
239                            // ~0.5 to 1 bit of additional noise, and thus not chosen here to ensure that the same
240                            // noise is kept with respect to the ideal functionality.
241                            tmp_dft_i.set_size(tsk.size() - ((dsize - di) as isize - 2).max(0) as usize);
242
243                            self.vec_znx_dft_copy(dsize, dsize - 1 - di, &mut tmp_a, 0, &ci_dft, col_i);
244                            if di == 0 && col_i == 1 {
245                                self.vmp_apply_dft_to_dft(&mut tmp_dft_i, &tmp_a, pmat, scratch_3);
246                            } else {
247                                self.vmp_apply_dft_to_dft_add(&mut tmp_dft_i, &tmp_a, pmat, di, scratch_3);
248                            }
249                        }
250                    }
251                }
252
253                // Adds -(sum a[i] * s[i]) + m)  on the i-th column of tmp_idft_i
254                //
255                // (-(x0s0 + x1s1 + x2s2) + a0s0s0 + a1s0s1 + a2s0s2, x0, x1, x2)
256                // +
257                // (0, -(a0s0 + a1s1 + a2s2) + M[i], 0, 0)
258                // =
259                // (-(x0s0 + x1s1 + x2s2) + s0(a0s0 + a1s1 + a2s2), x0 -(a0s0 + a1s1 + a2s2) + M[i], x1, x2)
260                // =
261                // (-(x0s0 + x1s1 + x2s2), x0 + M[i], x1, x2)
262                self.vec_znx_dft_add_inplace(&mut tmp_dft_i, col_j, &ci_dft, 0);
263                let (mut tmp_idft, scratch_3) = scratch_2.take_vec_znx_big(self, 1, tsk.size());
264                for i in 0..cols {
265                    self.vec_znx_idft_apply_tmpa(&mut tmp_idft, 0, &mut tmp_dft_i, i);
266                    self.vec_znx_big_normalize(
267                        basek_in,
268                        &mut res.at_mut(row_i, col_j).data,
269                        i,
270                        basek_tsk,
271                        &tmp_idft,
272                        0,
273                        scratch_3,
274                    );
275                }
276            }
277        }
278    }
279}