poulpy/rlwe/src/gadget_product.rs
rlwe/src/gadget_product.rsRaw
1use crate::{
2 ciphertext::Ciphertext,
3 elem::{Elem, ElemCommon, ElemVecZnx, VecZnxCommon},
4 parameters::Parameters,
5};
6use base2k::{Module, VecZnxDft, VecZnxDftOps, VmpPMat, VmpPMatOps};
7use std::cmp::min;
8
9pub fn gadget_product_tmp_bytes(
10 module: &Module,
11 log_base2k: usize,
12 res_log_q: usize,
13 in_log_q: usize,
14 gct_rows: usize,
15 gct_log_q: usize,
16) -> usize {
17 let gct_cols: usize = (gct_log_q + log_base2k - 1) / log_base2k;
18 let in_cols: usize = (in_log_q + log_base2k - 1) / log_base2k;
19 let out_cols: usize = (res_log_q + log_base2k - 1) / log_base2k;
20 module.vmp_apply_dft_to_dft_tmp_bytes(out_cols, in_cols, gct_rows, gct_cols)
21}
22
23impl Parameters {
24 pub fn gadget_product_tmp_bytes(
25 &self,
26 res_log_q: usize,
27 in_log_q: usize,
28 gct_rows: usize,
29 gct_log_q: usize,
30 ) -> usize {
31 gadget_product_tmp_bytes(
32 self.module(),
33 self.log_base2k(),
34 res_log_q,
35 in_log_q,
36 gct_rows,
37 gct_log_q,
38 )
39 }
40}
41
42/// Evaluates the gadget product res <- a x b.
43///
44/// # Arguments
45///
46/// * `module`: backend support for operations mod (X^N + 1).
47/// * `res`: an [Elem] to store (-cs + m * a + e, c) with res_ncols cols.
48/// * `a`: a [VecZnx] of a_ncols cols.
49/// * `b`: a [Ciphertext<VmpPMat>] as a vector of (-Bs + m * 2^{-k} + E, B)
50/// containing b_nrows [VecZnx], each of b_ncols cols.
51///
52/// # Computation
53///
54/// res = sum[min(a_ncols, b_nrows)] decomp(a, i) * (-B[i]s + m * 2^{-k*i} + E[i], B[i])
55/// = (cs + m * a + e, c) with min(res_cols, b_cols) cols.
56pub fn gadget_product_core<T>(
57 module: &Module,
58 res_dft_0: &mut VecZnxDft,
59 res_dft_1: &mut VecZnxDft,
60 a: &T,
61 a_cols: usize,
62 b: &Ciphertext<VmpPMat>,
63 b_cols: usize,
64 tmp_bytes: &mut [u8],
65) where
66 T: VecZnxCommon<Owned = T>,
67 Elem<T>: ElemVecZnx<T>,
68{
69 assert!(b_cols <= b.cols());
70 module.vec_znx_dft(res_dft_1, a, min(a_cols, b_cols));
71 module.vmp_apply_dft_to_dft(res_dft_0, res_dft_1, b.at(0), tmp_bytes);
72 module.vmp_apply_dft_to_dft_inplace(res_dft_1, b.at(1), tmp_bytes);
73}
74
75/*
76// res_big[a * (G0|G1)] <- IDFT(res_dft[a * (G0|G1)])
77module.vec_znx_idft_tmp_a(&mut res_big_0, &mut res_dft_0, b_cols);
78module.vec_znx_idft_tmp_a(&mut res_big_1, &mut res_dft_1, b_cols);
79
80// res_big <- res[0] + res_big[a*G0]
81module.vec_znx_big_add_small_inplace(&mut res_big_0, res.at(0));
82module.vec_znx_big_normalize(log_base2k, res.at_mut(0), &res_big_0, tmp_bytes_carry);
83
84if OVERWRITE {
85 // res[1] = normalize(res_big[a*G1])
86 module.vec_znx_big_normalize(log_base2k, res.at_mut(1), &res_big_1, tmp_bytes_carry);
87} else {
88 // res[1] = normalize(res_big[a*G1] + res[1])
89 module.vec_znx_big_add_small_inplace(&mut res_big_1, res.at(1));
90 module.vec_znx_big_normalize(log_base2k, res.at_mut(1), &res_big_1, tmp_bytes_carry);
91}
92*/
93
94#[cfg(test)]
95mod test {
96 use crate::{
97 ciphertext::{Ciphertext, new_gadget_ciphertext},
98 decryptor::decrypt_rlwe,
99 elem::{Elem, ElemCommon, ElemVecZnx},
100 encryptor::encrypt_grlwe_sk,
101 gadget_product::gadget_product_core,
102 keys::SecretKey,
103 parameters::{Parameters, ParametersLiteral},
104 plaintext::Plaintext,
105 };
106 use base2k::{
107 FFT64, Infos, Sampling, SvpPPolOps, VecZnx, VecZnxApi, VecZnxBig, VecZnxBigOps, VecZnxDft,
108 VecZnxDftOps, VecZnxOps, VmpPMat, alloc_aligned_u8,
109 };
110 use sampling::source::{Source, new_seed};
111
112 #[test]
113 fn test_gadget_product_core() {
114 let log_base2k: usize = 10;
115 let q_cols: usize = 7;
116 let p_cols: usize = 1;
117
118 // Basic parameters with enough limbs to test edge cases
119 let params_lit: ParametersLiteral = ParametersLiteral {
120 log_n: 12,
121 log_q: q_cols * log_base2k,
122 log_p: p_cols * log_base2k,
123 log_base2k: log_base2k,
124 log_scale: 20,
125 xe: 3.2,
126 xs: 1 << 11,
127 };
128
129 let params: Parameters = Parameters::new::<FFT64>(¶ms_lit);
130
131 // scratch space
132 let mut tmp_bytes: Vec<u8> = alloc_aligned_u8(
133 params.decrypt_rlwe_tmp_byte(params.log_qp())
134 | params.encrypt_rlwe_sk_tmp_bytes(params.log_qp())
135 | params.gadget_product_tmp_bytes(
136 params.log_qp(),
137 params.log_qp(),
138 params.cols_qp(),
139 params.log_qp(),
140 )
141 | params.encrypt_grlwe_sk_tmp_bytes(params.cols_qp(), params.log_qp()),
142 );
143
144 // Samplers for public and private randomness
145 let mut source_xe: Source = Source::new(new_seed());
146 let mut source_xa: Source = Source::new(new_seed());
147 let mut source_xs: Source = Source::new(new_seed());
148
149 // Two secret keys
150 let mut sk0: SecretKey = SecretKey::new(params.module());
151 sk0.fill_ternary_hw(params.xs(), &mut source_xs);
152 let mut sk0_svp_ppol: base2k::SvpPPol = params.module().new_svp_ppol();
153 params.module().svp_prepare(&mut sk0_svp_ppol, &sk0.0);
154
155 let mut sk1: SecretKey = SecretKey::new(params.module());
156 sk1.fill_ternary_hw(params.xs(), &mut source_xs);
157 let mut sk1_svp_ppol: base2k::SvpPPol = params.module().new_svp_ppol();
158 params.module().svp_prepare(&mut sk1_svp_ppol, &sk1.0);
159
160 // The gadget ciphertext
161 let mut gadget_ct: Ciphertext<VmpPMat> = new_gadget_ciphertext(
162 params.module(),
163 log_base2k,
164 params.cols_qp(),
165 params.log_qp(),
166 );
167
168 // gct = [-b*sk1 + g(sk0) + e, b]
169 encrypt_grlwe_sk(
170 params.module(),
171 &mut gadget_ct,
172 &sk0.0,
173 &sk1_svp_ppol,
174 &mut source_xa,
175 &mut source_xe,
176 params.xe(),
177 &mut tmp_bytes,
178 );
179
180 // Intermediate buffers
181 let mut res_dft_0: VecZnxDft = params.module().new_vec_znx_dft(gadget_ct.cols());
182 let mut res_dft_1: VecZnxDft = params.module().new_vec_znx_dft(gadget_ct.cols());
183 let mut res_big_0: VecZnxBig = res_dft_0.as_vec_znx_big();
184 let mut res_big_1: VecZnxBig = res_dft_1.as_vec_znx_big();
185
186 // Input polynopmial, uniformly distributed
187 let mut a: VecZnx = params.module().new_vec_znx(params.cols_q());
188 params
189 .module()
190 .fill_uniform(log_base2k, &mut a, params.cols_q(), &mut source_xa);
191
192 // res = g^-1(a) * gct
193 let mut elem_res: Elem<VecZnx> =
194 Elem::<VecZnx>::new(params.module(), log_base2k, params.log_qp(), 2);
195
196 // Ideal output = a * s
197 let mut a_dft: VecZnxDft = params.module().new_vec_znx_dft(a.cols());
198 let mut a_big: VecZnxBig = a_dft.as_vec_znx_big();
199 let mut a_times_s: VecZnx = params.module().new_vec_znx(a.cols());
200
201 // a * sk0
202 params
203 .module()
204 .svp_apply_dft(&mut a_dft, &sk0_svp_ppol, &a, a.cols());
205 params
206 .module()
207 .vec_znx_idft_tmp_a(&mut a_big, &mut a_dft, a.cols());
208 params.module().vec_znx_big_normalize(
209 params.log_base2k(),
210 &mut a_times_s,
211 &a_big,
212 &mut tmp_bytes,
213 );
214
215 // Plaintext for decrypted output of gadget product
216 let mut pt: Plaintext<VecZnx> =
217 Plaintext::<VecZnx>::new(params.module(), params.log_base2k(), params.log_qp());
218
219 // Iterates over all possible cols values for input/output polynomials and gadget ciphertext.
220
221 (1..a.cols() + 1).for_each(|a_cols| {
222 (1..gadget_ct.cols() + 1).for_each(|b_cols| {
223 pt.elem_mut().zero();
224 elem_res.zero();
225
226 //let b_cols: usize = min(a_cols+1, gadget_ct.cols());
227
228 println!("a_cols: {} b_cols: {}", a_cols, b_cols);
229
230 // res_dft_0 = DFT(gct_[0] * ct[1] = a * (-bs' + s + e) = -cs' + as + e')
231 // res_dft_1 = DFT(gct_[1] * ct[1] = a * b = c)
232 gadget_product_core(
233 params.module(),
234 &mut res_dft_0,
235 &mut res_dft_1,
236 &a,
237 a_cols,
238 &gadget_ct,
239 b_cols,
240 &mut tmp_bytes,
241 );
242
243 // res_big_0 = IDFT(res_dft_0)
244 params
245 .module()
246 .vec_znx_idft_tmp_a(&mut res_big_0, &mut res_dft_0, b_cols);
247 // res_big_1 = IDFT(res_dft_1);
248 params
249 .module()
250 .vec_znx_idft_tmp_a(&mut res_big_1, &mut res_dft_1, b_cols);
251
252 // res_big_0 = normalize(res_big_0)
253 params.module().vec_znx_big_normalize(
254 log_base2k,
255 elem_res.at_mut(0),
256 &res_big_0,
257 &mut tmp_bytes,
258 );
259
260 // res_big_1 = normalize(res_big_1)
261 params.module().vec_znx_big_normalize(
262 log_base2k,
263 elem_res.at_mut(1),
264 &res_big_1,
265 &mut tmp_bytes,
266 );
267
268 // <(-c*sk1 + a*sk0 + e, a), (1, sk1)> = a*sk0 + e
269 decrypt_rlwe(
270 params.module(),
271 pt.elem_mut(),
272 &elem_res,
273 &sk1_svp_ppol,
274 &mut tmp_bytes,
275 );
276
277 // a * sk0 + e - a*sk0 = e
278 params
279 .module()
280 .vec_znx_sub_inplace(pt.at_mut(0), &mut a_times_s);
281 pt.at_mut(0).normalize(log_base2k, &mut tmp_bytes);
282
283 //pt.at(0).print(pt.elem().cols(), 16);
284
285 let noise_have: f64 = pt.at(0).std(log_base2k).log2();
286
287 let var_a_err: f64;
288
289 if a_cols < a.cols() {
290 var_a_err = 1f64 / 12f64;
291 } else {
292 var_a_err = 0f64;
293 }
294
295 let a_logq: usize = a_cols * log_base2k;
296 let b_logq: usize = b_cols * log_base2k;
297 let var_msg: f64 = params.xs() as f64;
298
299 let noise_pred: f64 =
300 params.noise_grlwe_product(var_msg, var_a_err, a_logq, b_logq);
301
302 assert!(noise_have <= noise_pred + 1.0);
303
304 println!("noise_pred: {}", noise_have);
305 println!("noise_have: {}", noise_pred);
306 });
307 });
308 }
309}
310
311impl Parameters {
312 pub fn noise_grlwe_product(
313 &self,
314 var_msg: f64,
315 var_a_err: f64,
316 a_logq: usize,
317 b_logq: usize,
318 ) -> f64 {
319 let n: f64 = self.n() as f64;
320 let var_xs: f64 = self.xs() as f64;
321
322 let var_gct_err_lhs: f64;
323 let var_gct_err_rhs: f64;
324 if b_logq < self.log_qp() {
325 let var_round: f64 = 1f64 / 12f64;
326 var_gct_err_lhs = var_round;
327 var_gct_err_rhs = var_round;
328 } else {
329 var_gct_err_lhs = self.xe() * self.xe();
330 var_gct_err_rhs = 0f64;
331 }
332
333 noise_grlwe_product(
334 n,
335 self.log_base2k(),
336 var_xs,
337 var_msg,
338 var_a_err,
339 var_gct_err_lhs,
340 var_gct_err_rhs,
341 a_logq,
342 b_logq,
343 )
344 }
345}
346
347pub fn noise_grlwe_product(
348 n: f64,
349 log_base2k: usize,
350 var_xs: f64,
351 var_msg: f64,
352 var_a_err: f64,
353 var_gct_err_lhs: f64,
354 var_gct_err_rhs: f64,
355 a_logq: usize,
356 b_logq: usize,
357) -> f64 {
358 let a_logq: usize = min(a_logq, b_logq);
359 let a_cols: usize = (a_logq + log_base2k - 1) / log_base2k;
360
361 let b_scale = 2.0f64.powi(b_logq as i32);
362 let a_scale: f64 = 2.0f64.powi((b_logq - a_logq) as i32);
363
364 let base: f64 = (1 << (log_base2k)) as f64;
365 let var_base: f64 = base * base / 12f64;
366
367 // lhs = a_cols * n * (var_base * var_gct_err_lhs + var_e_a * var_msg * p^2)
368 // rhs = a_cols * n * var_base * var_gct_err_rhs * var_xs
369 let mut noise: f64 =
370 (a_cols as f64) * n * var_base * (var_gct_err_lhs + var_xs * var_gct_err_rhs);
371 noise += var_msg * var_a_err * a_scale * a_scale;
372 noise = noise.sqrt();
373 noise /= b_scale;
374 noise.log2().min(-1.0) // max noise is [-2^{-1}, 2^{-1}]
375}