arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-core/src/layouts/compressed/gglwe_tsk.rs
poulpy-core/src/layouts/compressed/gglwe_tsk.rsRaw
  1use poulpy_hal::{
  2    layouts::{Backend, Data, DataMut, DataRef, FillUniform, Module, ReaderFrom, WriterTo},
  3    source::Source,
  4};
  5
  6use crate::layouts::{
  7    Base2K, Degree, Dnum, Dsize, GGLWEInfos, GLWEInfos, LWEInfos, Rank, TensorKey, TensorKeyToMut, TorusPrecision,
  8    compressed::{
  9        GLWESwitchingKeyCompressed, GLWESwitchingKeyCompressedAlloc, GLWESwitchingKeyCompressedToMut,
 10        GLWESwitchingKeyCompressedToRef, GLWESwitchingKeyDecompress,
 11    },
 12};
 13use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
 14use std::fmt;
 15
 16#[derive(PartialEq, Eq, Clone)]
 17pub struct TensorKeyCompressed<D: Data> {
 18    pub(crate) keys: Vec<GLWESwitchingKeyCompressed<D>>,
 19}
 20
 21impl<D: Data> LWEInfos for TensorKeyCompressed<D> {
 22    fn n(&self) -> Degree {
 23        self.keys[0].n()
 24    }
 25
 26    fn base2k(&self) -> Base2K {
 27        self.keys[0].base2k()
 28    }
 29
 30    fn k(&self) -> TorusPrecision {
 31        self.keys[0].k()
 32    }
 33    fn size(&self) -> usize {
 34        self.keys[0].size()
 35    }
 36}
 37impl<D: Data> GLWEInfos for TensorKeyCompressed<D> {
 38    fn rank(&self) -> Rank {
 39        self.rank_out()
 40    }
 41}
 42
 43impl<D: Data> GGLWEInfos for TensorKeyCompressed<D> {
 44    fn rank_in(&self) -> Rank {
 45        self.rank_out()
 46    }
 47
 48    fn rank_out(&self) -> Rank {
 49        self.keys[0].rank_out()
 50    }
 51
 52    fn dsize(&self) -> Dsize {
 53        self.keys[0].dsize()
 54    }
 55
 56    fn dnum(&self) -> Dnum {
 57        self.keys[0].dnum()
 58    }
 59}
 60
 61impl<D: DataRef> fmt::Debug for TensorKeyCompressed<D> {
 62    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 63        write!(f, "{self}")
 64    }
 65}
 66
 67impl<D: DataMut> FillUniform for TensorKeyCompressed<D> {
 68    fn fill_uniform(&mut self, log_bound: usize, source: &mut Source) {
 69        self.keys
 70            .iter_mut()
 71            .for_each(|key: &mut GLWESwitchingKeyCompressed<D>| key.fill_uniform(log_bound, source))
 72    }
 73}
 74
 75impl<D: DataRef> fmt::Display for TensorKeyCompressed<D> {
 76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 77        writeln!(f, "(GLWETensorKeyCompressed)",)?;
 78        for (i, key) in self.keys.iter().enumerate() {
 79            write!(f, "{i}: {key}")?;
 80        }
 81        Ok(())
 82    }
 83}
 84
 85pub trait TensorKeyCompressedAlloc
 86where
 87    Self: GLWESwitchingKeyCompressedAlloc,
 88{
 89    fn alloc_tensor_key_compressed(
 90        &self,
 91        base2k: Base2K,
 92        k: TorusPrecision,
 93        rank: Rank,
 94        dnum: Dnum,
 95        dsize: Dsize,
 96    ) -> TensorKeyCompressed<Vec<u8>> {
 97        let pairs: u32 = (((rank.as_u32() + 1) * rank.as_u32()) >> 1).max(1);
 98        TensorKeyCompressed {
 99            keys: (0..pairs)
100                .map(|_| self.alloc_glwe_switching_key_compressed(base2k, k, Rank(1), rank, dnum, dsize))
101                .collect(),
102        }
103    }
104
105    fn alloc_tensor_key_compressed_from_infos<A>(&self, infos: &A) -> TensorKeyCompressed<Vec<u8>>
106    where
107        A: GGLWEInfos,
108    {
109        assert_eq!(
110            infos.rank_in(),
111            infos.rank_out(),
112            "rank_in != rank_out is not supported for GGLWETensorKeyCompressed"
113        );
114        self.alloc_tensor_key_compressed(
115            infos.base2k(),
116            infos.k(),
117            infos.rank(),
118            infos.dnum(),
119            infos.dsize(),
120        )
121    }
122
123    fn bytes_of_tensor_key_compressed(&self, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> usize {
124        let pairs: usize = (((rank.0 + 1) * rank.0) >> 1).max(1) as usize;
125        pairs * self.bytes_of_glwe_switching_key_compressed(base2k, k, Rank(1), dnum, dsize)
126    }
127
128    fn bytes_of_tensor_key_compressed_from_infos<A>(&self, infos: &A) -> usize
129    where
130        A: GGLWEInfos,
131    {
132        self.bytes_of_tensor_key_compressed(
133            infos.base2k(),
134            infos.k(),
135            infos.rank(),
136            infos.dnum(),
137            infos.dsize(),
138        )
139    }
140}
141
142impl TensorKeyCompressed<Vec<u8>> {
143    pub fn alloc_from_infos<A, M>(module: &M, infos: &A) -> Self
144    where
145        A: GGLWEInfos,
146        M: TensorKeyCompressedAlloc,
147    {
148        module.alloc_tensor_key_compressed_from_infos(infos)
149    }
150
151    pub fn alloc<M>(module: &M, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> Self
152    where
153        M: TensorKeyCompressedAlloc,
154    {
155        module.alloc_tensor_key_compressed(base2k, k, rank, dnum, dsize)
156    }
157
158    pub fn bytes_of_from_infos<A, M>(module: &M, infos: &A) -> usize
159    where
160        A: GGLWEInfos,
161        M: TensorKeyCompressedAlloc,
162    {
163        module.bytes_of_tensor_key_compressed_from_infos(infos)
164    }
165
166    pub fn bytes_of<M>(
167        module: &M,
168        base2k: Base2K,
169        k: TorusPrecision,
170        rank: Rank,
171        dnum: Dnum,
172        dsize: Dsize,
173    ) -> usize
174    where
175        M: TensorKeyCompressedAlloc,
176    {
177        module.bytes_of_tensor_key_compressed(base2k, k, rank, dnum, dsize)
178    }
179}
180
181impl<D: DataMut> ReaderFrom for TensorKeyCompressed<D> {
182    fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
183        let len: usize = reader.read_u64::<LittleEndian>()? as usize;
184        if self.keys.len() != len {
185            return Err(std::io::Error::new(
186                std::io::ErrorKind::InvalidData,
187                format!("self.keys.len()={} != read len={}", self.keys.len(), len),
188            ));
189        }
190        for key in &mut self.keys {
191            key.read_from(reader)?;
192        }
193        Ok(())
194    }
195}
196
197impl<D: DataRef> WriterTo for TensorKeyCompressed<D> {
198    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
199        writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
200        for key in &self.keys {
201            key.write_to(writer)?;
202        }
203        Ok(())
204    }
205}
206
207impl<D: DataMut> TensorKeyCompressed<D> {
208    pub(crate) fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GLWESwitchingKeyCompressed<D> {
209        if i > j {
210            std::mem::swap(&mut i, &mut j);
211        };
212        let rank: usize = self.rank_out().into();
213        &mut self.keys[i * rank + j - (i * (i + 1) / 2)]
214    }
215}
216
217pub trait TensorKeyDecompress
218where
219    Self: GLWESwitchingKeyDecompress,
220{
221    fn decompress_tensor_key<R, O>(&self, res: &mut R, other: &O)
222    where
223        R: TensorKeyToMut,
224        O: TensorKeyCompressedToRef,
225    {
226        let res: &mut TensorKey<&mut [u8]> = &mut res.to_mut();
227        let other: &TensorKeyCompressed<&[u8]> = &other.to_ref();
228
229        assert_eq!(
230            res.keys.len(),
231            other.keys.len(),
232            "invalid receiver: res.keys.len()={} != other.keys.len()={}",
233            res.keys.len(),
234            other.keys.len()
235        );
236
237        for (a, b) in res.keys.iter_mut().zip(other.keys.iter()) {
238            self.decompress_glwe_switching_key(a, b);
239        }
240    }
241}
242
243impl<B: Backend> TensorKeyDecompress for Module<B> where Self: GLWESwitchingKeyDecompress {}
244
245impl<D: DataMut> TensorKey<D> {
246    pub fn decompress<O, M>(&mut self, module: &M, other: &O)
247    where
248        O: TensorKeyCompressedToRef,
249        M: TensorKeyDecompress,
250    {
251        module.decompress_tensor_key(self, other);
252    }
253}
254
255pub trait TensorKeyCompressedToMut {
256    fn to_mut(&mut self) -> TensorKeyCompressed<&mut [u8]>;
257}
258
259impl<D: DataMut> TensorKeyCompressedToMut for TensorKeyCompressed<D>
260where
261    GLWESwitchingKeyCompressed<D>: GLWESwitchingKeyCompressedToMut,
262{
263    fn to_mut(&mut self) -> TensorKeyCompressed<&mut [u8]> {
264        TensorKeyCompressed {
265            keys: self.keys.iter_mut().map(|c| c.to_mut()).collect(),
266        }
267    }
268}
269
270pub trait TensorKeyCompressedToRef {
271    fn to_ref(&self) -> TensorKeyCompressed<&[u8]>;
272}
273
274impl<D: DataRef> TensorKeyCompressedToRef for TensorKeyCompressed<D>
275where
276    GLWESwitchingKeyCompressed<D>: GLWESwitchingKeyCompressedToRef,
277{
278    fn to_ref(&self) -> TensorKeyCompressed<&[u8]> {
279        TensorKeyCompressed {
280            keys: self.keys.iter().map(|c| c.to_ref()).collect(),
281        }
282    }
283}