arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-core/src/layouts/compressed/gglwe_ct.rs
poulpy-core/src/layouts/compressed/gglwe_ct.rsRaw
  1use poulpy_hal::{
  2    api::{VecZnxCopy, VecZnxFillUniform},
  3    layouts::{
  4        Backend, Data, DataMut, DataRef, FillUniform, MatZnx, MatZnxToMut, MatZnxToRef, Module, ReaderFrom, WriterTo, ZnxInfos,
  5    },
  6    source::Source,
  7};
  8
  9use crate::layouts::{
 10    Base2K, Degree, Dnum, Dsize, GGLWE, GGLWEInfos, GGLWEToMut, GLWEInfos, LWEInfos, Rank, TorusPrecision,
 11    compressed::{GLWECompressed, GLWEDecompress},
 12};
 13use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
 14use std::fmt;
 15
 16#[derive(PartialEq, Eq, Clone)]
 17pub struct GGLWECompressed<D: Data> {
 18    pub(crate) data: MatZnx<D>,
 19    pub(crate) base2k: Base2K,
 20    pub(crate) k: TorusPrecision,
 21    pub(crate) rank_out: Rank,
 22    pub(crate) dsize: Dsize,
 23    pub(crate) seed: Vec<[u8; 32]>,
 24}
 25
 26pub trait GGLWECompressedSeedMut {
 27    fn seed_mut(&mut self) -> &mut Vec<[u8; 32]>;
 28}
 29
 30impl<D: DataMut> GGLWECompressedSeedMut for GGLWECompressed<D> {
 31    fn seed_mut(&mut self) -> &mut Vec<[u8; 32]> {
 32        &mut self.seed
 33    }
 34}
 35
 36pub trait GGLWECompressedSeed {
 37    fn seed(&self) -> &Vec<[u8; 32]>;
 38}
 39
 40impl<D: DataRef> GGLWECompressedSeed for GGLWECompressed<D> {
 41    fn seed(&self) -> &Vec<[u8; 32]> {
 42        &self.seed
 43    }
 44}
 45impl<D: Data> LWEInfos for GGLWECompressed<D> {
 46    fn n(&self) -> Degree {
 47        Degree(self.data.n() as u32)
 48    }
 49
 50    fn base2k(&self) -> Base2K {
 51        self.base2k
 52    }
 53
 54    fn k(&self) -> TorusPrecision {
 55        self.k
 56    }
 57
 58    fn size(&self) -> usize {
 59        self.data.size()
 60    }
 61}
 62impl<D: Data> GLWEInfos for GGLWECompressed<D> {
 63    fn rank(&self) -> Rank {
 64        self.rank_out()
 65    }
 66}
 67
 68impl<D: Data> GGLWEInfos for GGLWECompressed<D> {
 69    fn rank_in(&self) -> Rank {
 70        Rank(self.data.cols_in() as u32)
 71    }
 72
 73    fn rank_out(&self) -> Rank {
 74        self.rank_out
 75    }
 76
 77    fn dsize(&self) -> Dsize {
 78        self.dsize
 79    }
 80
 81    fn dnum(&self) -> Dnum {
 82        Dnum(self.data.rows() as u32)
 83    }
 84}
 85
 86impl<D: DataRef> fmt::Debug for GGLWECompressed<D> {
 87    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 88        write!(f, "{self}")
 89    }
 90}
 91
 92impl<D: DataMut> FillUniform for GGLWECompressed<D> {
 93    fn fill_uniform(&mut self, log_bound: usize, source: &mut Source) {
 94        self.data.fill_uniform(log_bound, source);
 95    }
 96}
 97
 98impl<D: DataRef> fmt::Display for GGLWECompressed<D> {
 99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(
101            f,
102            "(GGLWECompressed: base2k={} k={} dsize={}) {}",
103            self.base2k.0, self.k.0, self.dsize.0, self.data
104        )
105    }
106}
107
108impl GGLWECompressed<Vec<u8>> {
109    pub fn alloc_from_infos<A>(infos: &A) -> Self
110    where
111        A: GGLWEInfos,
112    {
113        Self::alloc(
114            infos.n(),
115            infos.base2k(),
116            infos.k(),
117            infos.rank_in(),
118            infos.rank_out(),
119            infos.dnum(),
120            infos.dsize(),
121        )
122    }
123
124    pub fn alloc(n: Degree, base2k: Base2K, k: TorusPrecision, rank_in: Rank, rank_out: Rank, dnum: Dnum, dsize: Dsize) -> Self {
125        let size: usize = k.0.div_ceil(base2k.0) as usize;
126        debug_assert!(
127            size as u32 > dsize.0,
128            "invalid gglwe: ceil(k/base2k): {size} <= dsize: {}",
129            dsize.0
130        );
131
132        assert!(
133            dnum.0 * dsize.0 <= size as u32,
134            "invalid gglwe: dnum: {} * dsize:{} > ceil(k/base2k): {size}",
135            dnum.0,
136            dsize.0,
137        );
138
139        GGLWECompressed {
140            data: MatZnx::alloc(
141                n.into(),
142                dnum.into(),
143                rank_in.into(),
144                1,
145                k.0.div_ceil(base2k.0) as usize,
146            ),
147            k,
148            base2k,
149            dsize,
150            rank_out,
151            seed: vec![[0u8; 32]; (dnum.0 * rank_in.0) as usize],
152        }
153    }
154
155    pub fn bytes_of_from_infos<A>(infos: &A) -> usize
156    where
157        A: GGLWEInfos,
158    {
159        Self::bytes_of(
160            infos.n(),
161            infos.base2k(),
162            infos.k(),
163            infos.rank_in(),
164            infos.dnum(),
165            infos.dsize(),
166        )
167    }
168
169    pub fn bytes_of(n: Degree, base2k: Base2K, k: TorusPrecision, rank_in: Rank, dnum: Dnum, dsize: Dsize) -> usize {
170        let size: usize = k.0.div_ceil(base2k.0) as usize;
171        debug_assert!(
172            size as u32 > dsize.0,
173            "invalid gglwe: ceil(k/base2k): {size} <= dsize: {}",
174            dsize.0
175        );
176
177        assert!(
178            dnum.0 * dsize.0 <= size as u32,
179            "invalid gglwe: dnum: {} * dsize:{} > ceil(k/base2k): {size}",
180            dnum.0,
181            dsize.0,
182        );
183
184        MatZnx::bytes_of(
185            n.into(),
186            dnum.into(),
187            rank_in.into(),
188            1,
189            k.0.div_ceil(base2k.0) as usize,
190        )
191    }
192}
193
194impl<D: DataRef> GGLWECompressed<D> {
195    pub(crate) fn at(&self, row: usize, col: usize) -> GLWECompressed<&[u8]> {
196        let rank_in: usize = self.rank_in().into();
197        GLWECompressed {
198            data: self.data.at(row, col),
199            k: self.k,
200            base2k: self.base2k,
201            rank: self.rank_out,
202            seed: self.seed[rank_in * row + col],
203        }
204    }
205}
206
207impl<D: DataMut> GGLWECompressed<D> {
208    pub(crate) fn at_mut(&mut self, row: usize, col: usize) -> GLWECompressed<&mut [u8]> {
209        let rank_in: usize = self.rank_in().into();
210        GLWECompressed {
211            k: self.k,
212            base2k: self.base2k,
213            rank: self.rank_out,
214            data: self.data.at_mut(row, col),
215            seed: self.seed[rank_in * row + col], // Warning: value is copied and not borrow mut
216        }
217    }
218}
219
220impl<D: DataMut> ReaderFrom for GGLWECompressed<D> {
221    fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
222        self.k = TorusPrecision(reader.read_u32::<LittleEndian>()?);
223        self.base2k = Base2K(reader.read_u32::<LittleEndian>()?);
224        self.dsize = Dsize(reader.read_u32::<LittleEndian>()?);
225        self.rank_out = Rank(reader.read_u32::<LittleEndian>()?);
226        let seed_len: u32 = reader.read_u32::<LittleEndian>()?;
227        self.seed = vec![[0u8; 32]; seed_len as usize];
228        for s in &mut self.seed {
229            reader.read_exact(s)?;
230        }
231        self.data.read_from(reader)
232    }
233}
234
235impl<D: DataRef> WriterTo for GGLWECompressed<D> {
236    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
237        writer.write_u32::<LittleEndian>(self.k.into())?;
238        writer.write_u32::<LittleEndian>(self.base2k.into())?;
239        writer.write_u32::<LittleEndian>(self.dsize.into())?;
240        writer.write_u32::<LittleEndian>(self.rank_out.into())?;
241        writer.write_u32::<LittleEndian>(self.seed.len() as u32)?;
242        for s in &self.seed {
243            writer.write_all(s)?;
244        }
245        self.data.write_to(writer)
246    }
247}
248
249pub trait GGLWEDecompress
250where
251    Self: GLWEDecompress,
252{
253    fn decompress_gglwe<R, O>(&self, res: &mut R, other: &O)
254    where
255        R: GGLWEToMut,
256        O: GGLWECompressedToRef,
257    {
258        let res: &mut GGLWE<&mut [u8]> = &mut res.to_mut();
259        let other: &GGLWECompressed<&[u8]> = &other.to_ref();
260
261        assert_eq!(res.gglwe_layout(), other.gglwe_layout());
262
263        let rank_in: usize = res.rank_in().into();
264        let dnum: usize = res.dnum().into();
265
266        for row_i in 0..dnum {
267            for col_i in 0..rank_in {
268                self.decompress_glwe(&mut res.at_mut(row_i, col_i), &other.at(row_i, col_i));
269            }
270        }
271    }
272}
273
274impl<B: Backend> GGLWEDecompress for Module<B> where Self: VecZnxFillUniform + VecZnxCopy {}
275
276impl<D: DataMut> GGLWE<D> {
277    pub fn decompress<O, M>(&mut self, module: &M, other: &O)
278    where
279        O: GGLWECompressedToRef,
280        M: GGLWEDecompress,
281    {
282        module.decompress_gglwe(self, other);
283    }
284}
285
286pub trait GGLWECompressedToMut {
287    fn to_mut(&mut self) -> GGLWECompressed<&mut [u8]>;
288}
289
290impl<D: DataMut> GGLWECompressedToMut for GGLWECompressed<D> {
291    fn to_mut(&mut self) -> GGLWECompressed<&mut [u8]> {
292        GGLWECompressed {
293            k: self.k(),
294            base2k: self.base2k(),
295            dsize: self.dsize(),
296            seed: self.seed.clone(),
297            rank_out: self.rank_out,
298            data: self.data.to_mut(),
299        }
300    }
301}
302
303pub trait GGLWECompressedToRef {
304    fn to_ref(&self) -> GGLWECompressed<&[u8]>;
305}
306
307impl<D: DataRef> GGLWECompressedToRef for GGLWECompressed<D> {
308    fn to_ref(&self) -> GGLWECompressed<&[u8]> {
309        GGLWECompressed {
310            k: self.k(),
311            base2k: self.base2k(),
312            dsize: self.dsize(),
313            seed: self.seed.clone(),
314            rank_out: self.rank_out,
315            data: self.data.to_ref(),
316        }
317    }
318}