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