poly.rs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. #[cfg(target_feature = "avx2")]
  2. use std::arch::x86_64::*;
  3. use rand::distributions::Standard;
  4. use rand::Rng;
  5. use std::cell::RefCell;
  6. use std::ops::{Add, Mul, Neg};
  7. use crate::{aligned_memory::*, arith::*, discrete_gaussian::*, ntt::*, params::*, util::*};
  8. const SCRATCH_SPACE: usize = 8192;
  9. thread_local!(static SCRATCH: RefCell<AlignedMemory64> = RefCell::new(AlignedMemory64::new(SCRATCH_SPACE)));
  10. pub trait PolyMatrix<'a> {
  11. fn is_ntt(&self) -> bool;
  12. fn get_rows(&self) -> usize;
  13. fn get_cols(&self) -> usize;
  14. fn get_params(&self) -> &Params;
  15. fn num_words(&self) -> usize;
  16. fn zero(params: &'a Params, rows: usize, cols: usize) -> Self;
  17. fn random(params: &'a Params, rows: usize, cols: usize) -> Self;
  18. fn random_rng<T: Rng>(params: &'a Params, rows: usize, cols: usize, rng: &mut T) -> Self;
  19. fn as_slice(&self) -> &[u64];
  20. fn as_mut_slice(&mut self) -> &mut [u64];
  21. fn zero_out(&mut self) {
  22. for item in self.as_mut_slice() {
  23. *item = 0;
  24. }
  25. }
  26. fn get_poly(&self, row: usize, col: usize) -> &[u64] {
  27. let num_words = self.num_words();
  28. let start = (row * self.get_cols() + col) * num_words;
  29. &self.as_slice()[start..start + num_words]
  30. }
  31. fn get_poly_mut(&mut self, row: usize, col: usize) -> &mut [u64] {
  32. let num_words = self.num_words();
  33. let start = (row * self.get_cols() + col) * num_words;
  34. &mut self.as_mut_slice()[start..start + num_words]
  35. }
  36. fn copy_into(&mut self, p: &Self, target_row: usize, target_col: usize) {
  37. assert!(target_row < self.get_rows());
  38. assert!(target_col < self.get_cols());
  39. assert!(target_row + p.get_rows() <= self.get_rows());
  40. assert!(target_col + p.get_cols() <= self.get_cols());
  41. for r in 0..p.get_rows() {
  42. for c in 0..p.get_cols() {
  43. let pol_src = p.get_poly(r, c);
  44. let pol_dst = self.get_poly_mut(target_row + r, target_col + c);
  45. pol_dst.copy_from_slice(pol_src);
  46. }
  47. }
  48. }
  49. fn submatrix(&self, target_row: usize, target_col: usize, rows: usize, cols: usize) -> Self;
  50. fn pad_top(&self, pad_rows: usize) -> Self;
  51. }
  52. pub struct PolyMatrixRaw<'a> {
  53. pub params: &'a Params,
  54. pub rows: usize,
  55. pub cols: usize,
  56. pub data: AlignedMemory64,
  57. }
  58. pub struct PolyMatrixNTT<'a> {
  59. pub params: &'a Params,
  60. pub rows: usize,
  61. pub cols: usize,
  62. pub data: AlignedMemory64,
  63. }
  64. impl<'a> PolyMatrix<'a> for PolyMatrixRaw<'a> {
  65. fn is_ntt(&self) -> bool {
  66. false
  67. }
  68. fn get_rows(&self) -> usize {
  69. self.rows
  70. }
  71. fn get_cols(&self) -> usize {
  72. self.cols
  73. }
  74. fn get_params(&self) -> &Params {
  75. &self.params
  76. }
  77. fn as_slice(&self) -> &[u64] {
  78. self.data.as_slice()
  79. }
  80. fn as_mut_slice(&mut self) -> &mut [u64] {
  81. self.data.as_mut_slice()
  82. }
  83. fn num_words(&self) -> usize {
  84. self.params.poly_len
  85. }
  86. fn zero(params: &'a Params, rows: usize, cols: usize) -> PolyMatrixRaw<'a> {
  87. let num_coeffs = rows * cols * params.poly_len;
  88. let data = AlignedMemory64::new(num_coeffs);
  89. PolyMatrixRaw {
  90. params,
  91. rows,
  92. cols,
  93. data,
  94. }
  95. }
  96. fn random_rng<T: Rng>(params: &'a Params, rows: usize, cols: usize, rng: &mut T) -> Self {
  97. let mut iter = rng.sample_iter(&Standard);
  98. let mut out = PolyMatrixRaw::zero(params, rows, cols);
  99. for r in 0..rows {
  100. for c in 0..cols {
  101. for i in 0..params.poly_len {
  102. let val: u64 = iter.next().unwrap();
  103. out.get_poly_mut(r, c)[i] = val % params.modulus;
  104. }
  105. }
  106. }
  107. out
  108. }
  109. fn random(params: &'a Params, rows: usize, cols: usize) -> Self {
  110. let mut rng = rand::thread_rng();
  111. Self::random_rng(params, rows, cols, &mut rng)
  112. }
  113. fn pad_top(&self, pad_rows: usize) -> Self {
  114. let mut padded = Self::zero(self.params, self.rows + pad_rows, self.cols);
  115. padded.copy_into(&self, pad_rows, 0);
  116. padded
  117. }
  118. fn submatrix(&self, target_row: usize, target_col: usize, rows: usize, cols: usize) -> Self {
  119. let mut m = Self::zero(self.params, rows, cols);
  120. assert!(target_row < self.rows);
  121. assert!(target_col < self.cols);
  122. assert!(target_row + rows <= self.rows);
  123. assert!(target_col + cols <= self.cols);
  124. for r in 0..rows {
  125. for c in 0..cols {
  126. let pol_src = self.get_poly(target_row + r, target_col + c);
  127. let pol_dst = m.get_poly_mut(r, c);
  128. pol_dst.copy_from_slice(pol_src);
  129. }
  130. }
  131. m
  132. }
  133. }
  134. impl<'a> Clone for PolyMatrixRaw<'a> {
  135. fn clone(&self) -> Self {
  136. let mut data_clone = AlignedMemory64::new(self.data.len());
  137. data_clone
  138. .as_mut_slice()
  139. .copy_from_slice(self.data.as_slice());
  140. PolyMatrixRaw {
  141. params: self.params,
  142. rows: self.rows,
  143. cols: self.cols,
  144. data: data_clone,
  145. }
  146. }
  147. }
  148. impl<'a> PolyMatrixRaw<'a> {
  149. pub fn identity(params: &'a Params, rows: usize, cols: usize) -> PolyMatrixRaw<'a> {
  150. let num_coeffs = rows * cols * params.poly_len;
  151. let mut data = AlignedMemory::new(num_coeffs);
  152. for r in 0..rows {
  153. let c = r;
  154. let idx = r * cols * params.poly_len + c * params.poly_len;
  155. data[idx] = 1;
  156. }
  157. PolyMatrixRaw {
  158. params,
  159. rows,
  160. cols,
  161. data,
  162. }
  163. }
  164. pub fn noise(params: &'a Params, rows: usize, cols: usize, dg: &DiscreteGaussian) -> Self {
  165. let mut out = PolyMatrixRaw::zero(params, rows, cols);
  166. dg.sample_matrix(&mut out);
  167. out
  168. }
  169. pub fn ntt(&self) -> PolyMatrixNTT<'a> {
  170. to_ntt_alloc(&self)
  171. }
  172. pub fn reduce_mod(&mut self, modulus: u64) {
  173. for r in 0..self.rows {
  174. for c in 0..self.cols {
  175. for z in 0..self.params.poly_len {
  176. self.get_poly_mut(r, c)[z] %= modulus;
  177. }
  178. }
  179. }
  180. }
  181. pub fn apply_func<F: Fn(u64) -> u64>(&mut self, func: F) {
  182. for r in 0..self.rows {
  183. for c in 0..self.cols {
  184. let pol_mut = self.get_poly_mut(r, c);
  185. for el in pol_mut {
  186. *el = func(*el);
  187. }
  188. }
  189. }
  190. }
  191. pub fn to_vec(&self, modulus_bits: usize, num_coeffs: usize) -> Vec<u8> {
  192. let sz_bits = self.rows * self.cols * num_coeffs * modulus_bits;
  193. let sz_bytes = f64::ceil((sz_bits as f64) / 8f64) as usize + 32;
  194. let sz_bytes_roundup_16 = ((sz_bytes + 15) / 16) * 16;
  195. let mut data = vec![0u8; sz_bytes_roundup_16];
  196. let mut bit_offs = 0;
  197. for r in 0..self.rows {
  198. for c in 0..self.cols {
  199. for z in 0..num_coeffs {
  200. write_arbitrary_bits(
  201. data.as_mut_slice(),
  202. self.get_poly(r, c)[z],
  203. bit_offs,
  204. modulus_bits,
  205. );
  206. bit_offs += modulus_bits;
  207. }
  208. // round bit_offs down to nearest byte boundary
  209. bit_offs = (bit_offs / 8) * 8
  210. }
  211. }
  212. data
  213. }
  214. pub fn single_value(params: &'a Params, value: u64) -> PolyMatrixRaw<'a> {
  215. let mut out = Self::zero(params, 1, 1);
  216. out.data[0] = value;
  217. out
  218. }
  219. }
  220. impl<'a> PolyMatrix<'a> for PolyMatrixNTT<'a> {
  221. fn is_ntt(&self) -> bool {
  222. true
  223. }
  224. fn get_rows(&self) -> usize {
  225. self.rows
  226. }
  227. fn get_cols(&self) -> usize {
  228. self.cols
  229. }
  230. fn get_params(&self) -> &Params {
  231. &self.params
  232. }
  233. fn as_slice(&self) -> &[u64] {
  234. self.data.as_slice()
  235. }
  236. fn as_mut_slice(&mut self) -> &mut [u64] {
  237. self.data.as_mut_slice()
  238. }
  239. fn num_words(&self) -> usize {
  240. self.params.poly_len * self.params.crt_count
  241. }
  242. fn zero(params: &'a Params, rows: usize, cols: usize) -> PolyMatrixNTT<'a> {
  243. let num_coeffs = rows * cols * params.poly_len * params.crt_count;
  244. let data = AlignedMemory::new(num_coeffs);
  245. PolyMatrixNTT {
  246. params,
  247. rows,
  248. cols,
  249. data,
  250. }
  251. }
  252. fn random_rng<T: Rng>(params: &'a Params, rows: usize, cols: usize, rng: &mut T) -> Self {
  253. let mut iter = rng.sample_iter(&Standard);
  254. let mut out = PolyMatrixNTT::zero(params, rows, cols);
  255. for r in 0..rows {
  256. for c in 0..cols {
  257. for i in 0..params.crt_count {
  258. for j in 0..params.poly_len {
  259. let idx = calc_index(&[i, j], &[params.crt_count, params.poly_len]);
  260. let val: u64 = iter.next().unwrap();
  261. out.get_poly_mut(r, c)[idx] = val % params.moduli[i];
  262. }
  263. }
  264. }
  265. }
  266. out
  267. }
  268. fn random(params: &'a Params, rows: usize, cols: usize) -> Self {
  269. let mut rng = rand::thread_rng();
  270. Self::random_rng(params, rows, cols, &mut rng)
  271. }
  272. fn pad_top(&self, pad_rows: usize) -> Self {
  273. let mut padded = Self::zero(self.params, self.rows + pad_rows, self.cols);
  274. padded.copy_into(&self, pad_rows, 0);
  275. padded
  276. }
  277. fn submatrix(&self, target_row: usize, target_col: usize, rows: usize, cols: usize) -> Self {
  278. let mut m = Self::zero(self.params, rows, cols);
  279. assert!(target_row < self.rows);
  280. assert!(target_col < self.cols);
  281. assert!(target_row + rows <= self.rows);
  282. assert!(target_col + cols <= self.cols);
  283. for r in 0..rows {
  284. for c in 0..cols {
  285. let pol_src = self.get_poly(target_row + r, target_col + c);
  286. let pol_dst = m.get_poly_mut(r, c);
  287. pol_dst.copy_from_slice(pol_src);
  288. }
  289. }
  290. m
  291. }
  292. }
  293. impl<'a> Clone for PolyMatrixNTT<'a> {
  294. fn clone(&self) -> Self {
  295. let mut data_clone = AlignedMemory64::new(self.data.len());
  296. data_clone
  297. .as_mut_slice()
  298. .copy_from_slice(self.data.as_slice());
  299. PolyMatrixNTT {
  300. params: self.params,
  301. rows: self.rows,
  302. cols: self.cols,
  303. data: data_clone,
  304. }
  305. }
  306. }
  307. impl<'a> PolyMatrixNTT<'a> {
  308. pub fn raw(&self) -> PolyMatrixRaw<'a> {
  309. from_ntt_alloc(&self)
  310. }
  311. }
  312. pub fn multiply_poly(params: &Params, res: &mut [u64], a: &[u64], b: &[u64]) {
  313. for c in 0..params.crt_count {
  314. for i in 0..params.poly_len {
  315. let idx = c * params.poly_len + i;
  316. res[idx] = multiply_modular(params, a[idx], b[idx], c);
  317. }
  318. }
  319. }
  320. pub fn multiply_add_poly(params: &Params, res: &mut [u64], a: &[u64], b: &[u64]) {
  321. for c in 0..params.crt_count {
  322. for i in 0..params.poly_len {
  323. let idx = c * params.poly_len + i;
  324. res[idx] = multiply_add_modular(params, a[idx], b[idx], res[idx], c);
  325. }
  326. }
  327. }
  328. pub fn add_poly(params: &Params, res: &mut [u64], a: &[u64], b: &[u64]) {
  329. for c in 0..params.crt_count {
  330. for i in 0..params.poly_len {
  331. let idx = c * params.poly_len + i;
  332. res[idx] = add_modular(params, a[idx], b[idx], c);
  333. }
  334. }
  335. }
  336. pub fn add_poly_into(params: &Params, res: &mut [u64], a: &[u64]) {
  337. for c in 0..params.crt_count {
  338. for i in 0..params.poly_len {
  339. let idx = c * params.poly_len + i;
  340. res[idx] = add_modular(params, res[idx], a[idx], c);
  341. }
  342. }
  343. }
  344. pub fn invert_poly(params: &Params, res: &mut [u64], a: &[u64]) {
  345. for i in 0..params.poly_len {
  346. res[i] = params.modulus - a[i];
  347. }
  348. }
  349. pub fn automorph_poly(params: &Params, res: &mut [u64], a: &[u64], t: usize) {
  350. let poly_len = params.poly_len;
  351. for i in 0..poly_len {
  352. let num = (i * t) / poly_len;
  353. let rem = (i * t) % poly_len;
  354. if num % 2 == 0 {
  355. res[rem] = a[i];
  356. } else {
  357. res[rem] = params.modulus - a[i];
  358. }
  359. }
  360. }
  361. #[cfg(target_feature = "avx2")]
  362. pub fn multiply_add_poly_avx(params: &Params, res: &mut [u64], a: &[u64], b: &[u64]) {
  363. for c in 0..params.crt_count {
  364. for i in (0..params.poly_len).step_by(4) {
  365. unsafe {
  366. let p_x = &a[c * params.poly_len + i] as *const u64;
  367. let p_y = &b[c * params.poly_len + i] as *const u64;
  368. let p_z = &mut res[c * params.poly_len + i] as *mut u64;
  369. let x = _mm256_load_si256(p_x as *const __m256i);
  370. let y = _mm256_load_si256(p_y as *const __m256i);
  371. let z = _mm256_load_si256(p_z as *const __m256i);
  372. let product = _mm256_mul_epu32(x, y);
  373. let out = _mm256_add_epi64(z, product);
  374. _mm256_store_si256(p_z as *mut __m256i, out);
  375. }
  376. }
  377. }
  378. }
  379. pub fn modular_reduce(params: &Params, res: &mut [u64]) {
  380. for c in 0..params.crt_count {
  381. for i in 0..params.poly_len {
  382. let idx = c * params.poly_len + i;
  383. res[idx] = barrett_coeff_u64(params, res[idx], c);
  384. }
  385. }
  386. }
  387. #[cfg(not(target_feature = "avx2"))]
  388. pub fn multiply(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT, b: &PolyMatrixNTT) {
  389. assert!(res.rows == a.rows);
  390. assert!(res.cols == b.cols);
  391. assert!(a.cols == b.rows);
  392. let params = res.params;
  393. for i in 0..a.rows {
  394. for j in 0..b.cols {
  395. for z in 0..params.poly_len * params.crt_count {
  396. res.get_poly_mut(i, j)[z] = 0;
  397. }
  398. for k in 0..a.cols {
  399. let params = res.params;
  400. let res_poly = res.get_poly_mut(i, j);
  401. let pol1 = a.get_poly(i, k);
  402. let pol2 = b.get_poly(k, j);
  403. multiply_add_poly(params, res_poly, pol1, pol2);
  404. }
  405. }
  406. }
  407. }
  408. #[cfg(target_feature = "avx2")]
  409. pub fn multiply(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT, b: &PolyMatrixNTT) {
  410. assert_eq!(res.rows, a.rows);
  411. assert_eq!(res.cols, b.cols);
  412. assert_eq!(a.cols, b.rows);
  413. let params = res.params;
  414. for i in 0..a.rows {
  415. for j in 0..b.cols {
  416. for z in 0..params.poly_len * params.crt_count {
  417. res.get_poly_mut(i, j)[z] = 0;
  418. }
  419. let res_poly = res.get_poly_mut(i, j);
  420. for k in 0..a.cols {
  421. let pol1 = a.get_poly(i, k);
  422. let pol2 = b.get_poly(k, j);
  423. multiply_add_poly_avx(params, res_poly, pol1, pol2);
  424. }
  425. modular_reduce(params, res_poly);
  426. }
  427. }
  428. }
  429. pub fn add(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT, b: &PolyMatrixNTT) {
  430. assert!(res.rows == a.rows);
  431. assert!(res.cols == a.cols);
  432. assert!(a.rows == b.rows);
  433. assert!(a.cols == b.cols);
  434. let params = res.params;
  435. for i in 0..a.rows {
  436. for j in 0..a.cols {
  437. let res_poly = res.get_poly_mut(i, j);
  438. let pol1 = a.get_poly(i, j);
  439. let pol2 = b.get_poly(i, j);
  440. add_poly(params, res_poly, pol1, pol2);
  441. }
  442. }
  443. }
  444. pub fn add_into(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT) {
  445. assert!(res.rows == a.rows);
  446. assert!(res.cols == a.cols);
  447. let params = res.params;
  448. for i in 0..res.rows {
  449. for j in 0..res.cols {
  450. let res_poly = res.get_poly_mut(i, j);
  451. let pol2 = a.get_poly(i, j);
  452. add_poly_into(params, res_poly, pol2);
  453. }
  454. }
  455. }
  456. pub fn add_into_at(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT, t_row: usize, t_col: usize) {
  457. let params = res.params;
  458. for i in 0..a.rows {
  459. for j in 0..a.cols {
  460. let res_poly = res.get_poly_mut(t_row + i, t_col + j);
  461. let pol2 = a.get_poly(i, j);
  462. add_poly_into(params, res_poly, pol2);
  463. }
  464. }
  465. }
  466. pub fn invert(res: &mut PolyMatrixRaw, a: &PolyMatrixRaw) {
  467. assert!(res.rows == a.rows);
  468. assert!(res.cols == a.cols);
  469. let params = res.params;
  470. for i in 0..a.rows {
  471. for j in 0..a.cols {
  472. let res_poly = res.get_poly_mut(i, j);
  473. let pol1 = a.get_poly(i, j);
  474. invert_poly(params, res_poly, pol1);
  475. }
  476. }
  477. }
  478. pub fn automorph<'a>(res: &mut PolyMatrixRaw<'a>, a: &PolyMatrixRaw<'a>, t: usize) {
  479. assert!(res.rows == a.rows);
  480. assert!(res.cols == a.cols);
  481. let params = res.params;
  482. for i in 0..a.rows {
  483. for j in 0..a.cols {
  484. let res_poly = res.get_poly_mut(i, j);
  485. let pol1 = a.get_poly(i, j);
  486. automorph_poly(params, res_poly, pol1, t);
  487. }
  488. }
  489. }
  490. pub fn automorph_alloc<'a>(a: &PolyMatrixRaw<'a>, t: usize) -> PolyMatrixRaw<'a> {
  491. let mut res = PolyMatrixRaw::zero(a.params, a.rows, a.cols);
  492. automorph(&mut res, a, t);
  493. res
  494. }
  495. pub fn stack<'a>(a: &PolyMatrixRaw<'a>, b: &PolyMatrixRaw<'a>) -> PolyMatrixRaw<'a> {
  496. assert_eq!(a.cols, b.cols);
  497. let mut c = PolyMatrixRaw::zero(a.params, a.rows + b.rows, a.cols);
  498. c.copy_into(a, 0, 0);
  499. c.copy_into(b, a.rows, 0);
  500. c
  501. }
  502. pub fn scalar_multiply(res: &mut PolyMatrixNTT, a: &PolyMatrixNTT, b: &PolyMatrixNTT) {
  503. assert_eq!(a.rows, 1);
  504. assert_eq!(a.cols, 1);
  505. let params = res.params;
  506. let pol2 = a.get_poly(0, 0);
  507. for i in 0..b.rows {
  508. for j in 0..b.cols {
  509. let res_poly = res.get_poly_mut(i, j);
  510. let pol1 = b.get_poly(i, j);
  511. multiply_poly(params, res_poly, pol1, pol2);
  512. }
  513. }
  514. }
  515. pub fn scalar_multiply_alloc<'a>(
  516. a: &PolyMatrixNTT<'a>,
  517. b: &PolyMatrixNTT<'a>,
  518. ) -> PolyMatrixNTT<'a> {
  519. let mut res = PolyMatrixNTT::zero(b.params, b.rows, b.cols);
  520. scalar_multiply(&mut res, a, b);
  521. res
  522. }
  523. pub fn single_poly<'a>(params: &'a Params, val: u64) -> PolyMatrixRaw<'a> {
  524. let mut res = PolyMatrixRaw::zero(params, 1, 1);
  525. res.get_poly_mut(0, 0)[0] = val;
  526. res
  527. }
  528. fn reduce_copy(params: &Params, out: &mut [u64], inp: &[u64]) {
  529. for n in 0..params.crt_count {
  530. for z in 0..params.poly_len {
  531. out[n * params.poly_len + z] = barrett_coeff_u64(params, inp[z], n);
  532. }
  533. }
  534. }
  535. pub fn to_ntt(a: &mut PolyMatrixNTT, b: &PolyMatrixRaw) {
  536. let params = a.params;
  537. for r in 0..a.rows {
  538. for c in 0..a.cols {
  539. let pol_src = b.get_poly(r, c);
  540. let pol_dst = a.get_poly_mut(r, c);
  541. reduce_copy(params, pol_dst, pol_src);
  542. ntt_forward(params, pol_dst);
  543. }
  544. }
  545. }
  546. pub fn to_ntt_no_reduce(a: &mut PolyMatrixNTT, b: &PolyMatrixRaw) {
  547. let params = a.params;
  548. for r in 0..a.rows {
  549. for c in 0..a.cols {
  550. let pol_src = b.get_poly(r, c);
  551. let pol_dst = a.get_poly_mut(r, c);
  552. for n in 0..params.crt_count {
  553. let idx = n * params.poly_len;
  554. pol_dst[idx..idx + params.poly_len].copy_from_slice(pol_src);
  555. }
  556. ntt_forward(params, pol_dst);
  557. }
  558. }
  559. }
  560. pub fn to_ntt_alloc<'a>(b: &PolyMatrixRaw<'a>) -> PolyMatrixNTT<'a> {
  561. let mut a = PolyMatrixNTT::zero(b.params, b.rows, b.cols);
  562. to_ntt(&mut a, b);
  563. a
  564. }
  565. pub fn from_ntt(a: &mut PolyMatrixRaw, b: &PolyMatrixNTT) {
  566. let params = a.params;
  567. SCRATCH.with(|scratch_cell| {
  568. let scratch_vec = &mut *scratch_cell.borrow_mut();
  569. let scratch = scratch_vec.as_mut_slice();
  570. for r in 0..a.rows {
  571. for c in 0..a.cols {
  572. let pol_src = b.get_poly(r, c);
  573. let pol_dst = a.get_poly_mut(r, c);
  574. scratch[0..pol_src.len()].copy_from_slice(pol_src);
  575. ntt_inverse(params, scratch);
  576. for z in 0..params.poly_len {
  577. pol_dst[z] = params.crt_compose(scratch, z);
  578. }
  579. }
  580. }
  581. });
  582. }
  583. pub fn from_ntt_alloc<'a>(b: &PolyMatrixNTT<'a>) -> PolyMatrixRaw<'a> {
  584. let mut a = PolyMatrixRaw::zero(b.params, b.rows, b.cols);
  585. from_ntt(&mut a, b);
  586. a
  587. }
  588. impl<'a, 'b> Neg for &'b PolyMatrixRaw<'a> {
  589. type Output = PolyMatrixRaw<'a>;
  590. fn neg(self) -> Self::Output {
  591. let mut out = PolyMatrixRaw::zero(self.params, self.rows, self.cols);
  592. invert(&mut out, self);
  593. out
  594. }
  595. }
  596. impl<'a, 'b> Mul for &'b PolyMatrixNTT<'a> {
  597. type Output = PolyMatrixNTT<'a>;
  598. fn mul(self, rhs: Self) -> Self::Output {
  599. let mut out = PolyMatrixNTT::zero(self.params, self.rows, rhs.cols);
  600. multiply(&mut out, self, rhs);
  601. out
  602. }
  603. }
  604. impl<'a, 'b> Add for &'b PolyMatrixNTT<'a> {
  605. type Output = PolyMatrixNTT<'a>;
  606. fn add(self, rhs: Self) -> Self::Output {
  607. let mut out = PolyMatrixNTT::zero(self.params, self.rows, self.cols);
  608. add(&mut out, self, rhs);
  609. out
  610. }
  611. }
  612. #[cfg(test)]
  613. mod test {
  614. use super::*;
  615. fn get_params() -> Params {
  616. get_test_params()
  617. }
  618. fn assert_all_zero(a: &[u64]) {
  619. for i in a {
  620. assert_eq!(*i, 0);
  621. }
  622. }
  623. #[test]
  624. fn sets_all_zeros() {
  625. let params = get_params();
  626. let m1 = PolyMatrixNTT::zero(&params, 2, 1);
  627. assert_all_zero(m1.as_slice());
  628. }
  629. #[test]
  630. fn multiply_correctness() {
  631. let params = get_params();
  632. let m1 = PolyMatrixNTT::zero(&params, 2, 1);
  633. let m2 = PolyMatrixNTT::zero(&params, 3, 2);
  634. let m3 = &m2 * &m1;
  635. assert_all_zero(m3.as_slice());
  636. }
  637. #[test]
  638. fn full_multiply_correctness() {
  639. let params = get_params();
  640. let mut m1 = PolyMatrixRaw::zero(&params, 1, 1);
  641. let mut m2 = PolyMatrixRaw::zero(&params, 1, 1);
  642. m1.get_poly_mut(0, 0)[1] = 100;
  643. m2.get_poly_mut(0, 0)[1] = 7;
  644. let m1_ntt = to_ntt_alloc(&m1);
  645. let m2_ntt = to_ntt_alloc(&m2);
  646. let m3_ntt = &m1_ntt * &m2_ntt;
  647. let m3 = from_ntt_alloc(&m3_ntt);
  648. assert_eq!(m3.get_poly(0, 0)[2], 700);
  649. }
  650. #[test]
  651. fn to_vec_correctness() {
  652. let params = get_params();
  653. let mut m1 = PolyMatrixRaw::zero(&params, 1, 1);
  654. for i in 0..params.poly_len {
  655. m1.data[i] = 1;
  656. }
  657. let modulus_bits = 9;
  658. let v = m1.to_vec(modulus_bits, params.poly_len);
  659. for i in 0..v.len() {
  660. println!("{:?}", v[i]);
  661. }
  662. let mut bit_offs = 0;
  663. for i in 0..params.poly_len {
  664. let val = read_arbitrary_bits(v.as_slice(), bit_offs, modulus_bits);
  665. assert_eq!(m1.data[i], val);
  666. bit_offs += modulus_bits;
  667. }
  668. }
  669. }