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, Dnum, Dsize, GGLWEInfos, GLWEInfos, LWEInfos, Rank, RingDegree, 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) -> RingDegree {
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>(module: &M, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> usize
167 where
168 M: TensorKeyCompressedAlloc,
169 {
170 module.bytes_of_tensor_key_compressed(base2k, k, rank, dnum, dsize)
171 }
172}
173
174impl<D: DataMut> ReaderFrom for TensorKeyCompressed<D> {
175 fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
176 let len: usize = reader.read_u64::<LittleEndian>()? as usize;
177 if self.keys.len() != len {
178 return Err(std::io::Error::new(
179 std::io::ErrorKind::InvalidData,
180 format!("self.keys.len()={} != read len={}", self.keys.len(), len),
181 ));
182 }
183 for key in &mut self.keys {
184 key.read_from(reader)?;
185 }
186 Ok(())
187 }
188}
189
190impl<D: DataRef> WriterTo for TensorKeyCompressed<D> {
191 fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
192 writer.write_u64::<LittleEndian>(self.keys.len() as u64)?;
193 for key in &self.keys {
194 key.write_to(writer)?;
195 }
196 Ok(())
197 }
198}
199
200impl<D: DataMut> TensorKeyCompressed<D> {
201 pub(crate) fn at_mut(&mut self, mut i: usize, mut j: usize) -> &mut GLWESwitchingKeyCompressed<D> {
202 if i > j {
203 std::mem::swap(&mut i, &mut j);
204 };
205 let rank: usize = self.rank_out().into();
206 &mut self.keys[i * rank + j - (i * (i + 1) / 2)]
207 }
208}
209
210pub trait TensorKeyDecompress
211where
212 Self: GLWESwitchingKeyDecompress,
213{
214 fn decompress_tensor_key<R, O>(&self, res: &mut R, other: &O)
215 where
216 R: TensorKeyToMut,
217 O: TensorKeyCompressedToRef,
218 {
219 let res: &mut TensorKey<&mut [u8]> = &mut res.to_mut();
220 let other: &TensorKeyCompressed<&[u8]> = &other.to_ref();
221
222 assert_eq!(
223 res.keys.len(),
224 other.keys.len(),
225 "invalid receiver: res.keys.len()={} != other.keys.len()={}",
226 res.keys.len(),
227 other.keys.len()
228 );
229
230 for (a, b) in res.keys.iter_mut().zip(other.keys.iter()) {
231 self.decompress_glwe_switching_key(a, b);
232 }
233 }
234}
235
236impl<B: Backend> TensorKeyDecompress for Module<B> where Self: GLWESwitchingKeyDecompress {}
237
238impl<D: DataMut> TensorKey<D> {
239 pub fn decompress<O, M>(&mut self, module: &M, other: &O)
240 where
241 O: TensorKeyCompressedToRef,
242 M: TensorKeyDecompress,
243 {
244 module.decompress_tensor_key(self, other);
245 }
246}
247
248pub trait TensorKeyCompressedToMut {
249 fn to_mut(&mut self) -> TensorKeyCompressed<&mut [u8]>;
250}
251
252impl<D: DataMut> TensorKeyCompressedToMut for TensorKeyCompressed<D>
253where
254 GLWESwitchingKeyCompressed<D>: GLWESwitchingKeyCompressedToMut,
255{
256 fn to_mut(&mut self) -> TensorKeyCompressed<&mut [u8]> {
257 TensorKeyCompressed {
258 keys: self.keys.iter_mut().map(|c| c.to_mut()).collect(),
259 }
260 }
261}
262
263pub trait TensorKeyCompressedToRef {
264 fn to_ref(&self) -> TensorKeyCompressed<&[u8]>;
265}
266
267impl<D: DataRef> TensorKeyCompressedToRef for TensorKeyCompressed<D>
268where
269 GLWESwitchingKeyCompressed<D>: GLWESwitchingKeyCompressedToRef,
270{
271 fn to_ref(&self) -> TensorKeyCompressed<&[u8]> {
272 TensorKeyCompressed {
273 keys: self.keys.iter().map(|c| c.to_ref()).collect(),
274 }
275 }
276}