arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/base2k/src/svp.rs
base2k/src/svp.rsRaw
  1use crate::ffi::svp::{self, svp_ppol_t};
  2use crate::ffi::vec_znx_dft::vec_znx_dft_t;
  3use crate::{assert_alignement, Module, VecZnx, VecZnxDft, BACKEND};
  4
  5use crate::{alloc_aligned, cast_mut, Infos};
  6use rand::seq::SliceRandom;
  7use rand_core::RngCore;
  8use rand_distr::{Distribution, WeightedIndex};
  9use sampling::source::Source;
 10
 11pub struct Scalar {
 12    pub n: usize,
 13    pub data: Vec<i64>,
 14    pub ptr: *mut i64,
 15}
 16
 17impl Module {
 18    pub fn new_scalar(&self) -> Scalar {
 19        Scalar::new(self.n())
 20    }
 21}
 22
 23impl Scalar {
 24    pub fn new(n: usize) -> Self {
 25        let mut data: Vec<i64> = alloc_aligned::<i64>(n);
 26        let ptr: *mut i64 = data.as_mut_ptr();
 27        Self {
 28            n: n,
 29            data: data,
 30            ptr: ptr,
 31        }
 32    }
 33
 34    pub fn n(&self) -> usize {
 35        self.n
 36    }
 37
 38    pub fn bytes_of(n: usize) -> usize {
 39        n * std::mem::size_of::<i64>()
 40    }
 41
 42    pub fn from_bytes(n: usize, bytes: &mut [u8]) -> Self {
 43        let size: usize = Self::bytes_of(n);
 44        debug_assert!(
 45            bytes.len() == size,
 46            "invalid buffer: bytes.len()={} < self.bytes_of(n={})={}",
 47            bytes.len(),
 48            n,
 49            size
 50        );
 51        #[cfg(debug_assertions)]
 52        {
 53            assert_alignement(bytes.as_ptr())
 54        }
 55        unsafe {
 56            let bytes_i64: &mut [i64] = cast_mut::<u8, i64>(bytes);
 57            let ptr: *mut i64 = bytes_i64.as_mut_ptr();
 58            Self {
 59                n: n,
 60                data: Vec::from_raw_parts(bytes_i64.as_mut_ptr(), bytes.len(), bytes.len()),
 61                ptr: ptr,
 62            }
 63        }
 64    }
 65
 66    pub fn from_bytes_borrow(n: usize, bytes: &mut [u8]) -> Self {
 67        let size: usize = Self::bytes_of(n);
 68        debug_assert!(
 69            bytes.len() == size,
 70            "invalid buffer: bytes.len()={} < self.bytes_of(n={})={}",
 71            bytes.len(),
 72            n,
 73            size
 74        );
 75        #[cfg(debug_assertions)]
 76        {
 77            assert_alignement(bytes.as_ptr())
 78        }
 79        let bytes_i64: &mut [i64] = cast_mut::<u8, i64>(bytes);
 80        let ptr: *mut i64 = bytes_i64.as_mut_ptr();
 81        Self {
 82            n: n,
 83            data: Vec::new(),
 84            ptr: ptr,
 85        }
 86    }
 87
 88    pub fn as_ptr(&self) -> *const i64 {
 89        self.ptr
 90    }
 91
 92    pub fn raw(&self) -> &[i64] {
 93        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.n) }
 94    }
 95
 96    pub fn fill_ternary_prob(&mut self, prob: f64, source: &mut Source) {
 97        let choices: [i64; 3] = [-1, 0, 1];
 98        let weights: [f64; 3] = [prob / 2.0, 1.0 - prob, prob / 2.0];
 99        let dist: WeightedIndex<f64> = WeightedIndex::new(&weights).unwrap();
100        self.data
101            .iter_mut()
102            .for_each(|x: &mut i64| *x = choices[dist.sample(source)]);
103    }
104
105    pub fn fill_ternary_hw(&mut self, hw: usize, source: &mut Source) {
106        assert!(hw <= self.n());
107        self.data[..hw]
108            .iter_mut()
109            .for_each(|x: &mut i64| *x = (((source.next_u32() & 1) as i64) << 1) - 1);
110        self.data.shuffle(source);
111    }
112
113    pub fn as_vec_znx(&self) -> VecZnx {
114        VecZnx {
115            n: self.n,
116            cols: 1,
117            data: Vec::new(),
118            ptr: self.ptr,
119        }
120    }
121}
122
123pub trait ScalarOps {
124    fn bytes_of_scalar(&self) -> usize;
125    fn new_scalar(&self) -> Scalar;
126    fn new_scalar_from_bytes(&self, bytes: &mut [u8]) -> Scalar;
127    fn new_scalar_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> Scalar;
128}
129impl ScalarOps for Module {
130    fn bytes_of_scalar(&self) -> usize {
131        Scalar::bytes_of(self.n())
132    }
133    fn new_scalar(&self) -> Scalar {
134        Scalar::new(self.n())
135    }
136    fn new_scalar_from_bytes(&self, bytes: &mut [u8]) -> Scalar {
137        Scalar::from_bytes(self.n(), bytes)
138    }
139    fn new_scalar_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> Scalar {
140        Scalar::from_bytes_borrow(self.n(), tmp_bytes)
141    }
142}
143
144pub struct SvpPPol {
145    pub n: usize,
146    pub data: Vec<u8>,
147    pub ptr: *mut u8,
148    pub backend: BACKEND,
149}
150
151/// A prepared [crate::Scalar] for [SvpPPolOps::svp_apply_dft].
152/// An [SvpPPol] an be seen as a [VecZnxDft] of one limb.
153impl SvpPPol {
154    pub fn new(module: &Module) -> Self {
155        module.new_svp_ppol()
156    }
157
158    /// Returns the ring degree of the [SvpPPol].
159    pub fn n(&self) -> usize {
160        self.n
161    }
162
163    pub fn bytes_of(module: &Module) -> usize {
164        module.bytes_of_svp_ppol()
165    }
166
167    pub fn from_bytes(module: &Module, bytes: &mut [u8]) -> SvpPPol {
168        #[cfg(debug_assertions)]
169        {
170            assert_alignement(bytes.as_ptr());
171            assert_eq!(bytes.len(), module.bytes_of_svp_ppol());
172        }
173        unsafe {
174            Self {
175                n: module.n(),
176                data: Vec::from_raw_parts(bytes.as_mut_ptr(), bytes.len(), bytes.len()),
177                ptr: bytes.as_mut_ptr(),
178                backend: module.backend(),
179            }
180        }
181    }
182
183    pub fn from_bytes_borrow(module: &Module, tmp_bytes: &mut [u8]) -> SvpPPol {
184        #[cfg(debug_assertions)]
185        {
186            assert_alignement(tmp_bytes.as_ptr());
187            assert_eq!(tmp_bytes.len(), module.bytes_of_svp_ppol());
188        }
189        Self {
190            n: module.n(),
191            data: Vec::new(),
192            ptr: tmp_bytes.as_mut_ptr(),
193            backend: module.backend(),
194        }
195    }
196
197    /// Returns the number of cols of the [SvpPPol], which is always 1.
198    pub fn cols(&self) -> usize {
199        1
200    }
201}
202
203pub trait SvpPPolOps {
204    /// Allocates a new [SvpPPol].
205    fn new_svp_ppol(&self) -> SvpPPol;
206
207    /// Returns the minimum number of bytes necessary to allocate
208    /// a new [SvpPPol] through [SvpPPol::from_bytes] ro.
209    fn bytes_of_svp_ppol(&self) -> usize;
210
211    /// Allocates a new [SvpPPol] from an array of bytes.
212    /// The array of bytes is owned by the [SvpPPol].
213    /// The method will panic if bytes.len() < [SvpPPolOps::bytes_of_svp_ppol]
214    fn new_svp_ppol_from_bytes(&self, bytes: &mut [u8]) -> SvpPPol;
215
216    /// Allocates a new [SvpPPol] from an array of bytes.
217    /// The array of bytes is borrowed by the [SvpPPol].
218    /// The method will panic if bytes.len() < [SvpPPolOps::bytes_of_svp_ppol]
219    fn new_svp_ppol_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> SvpPPol;
220
221    /// Prepares a [crate::Scalar] for a [SvpPPolOps::svp_apply_dft].
222    fn svp_prepare(&self, svp_ppol: &mut SvpPPol, a: &Scalar);
223
224    /// Applies the [SvpPPol] x [VecZnxDft] product, where each limb of
225    /// the [VecZnxDft] is multiplied with [SvpPPol].
226    fn svp_apply_dft(&self, c: &mut VecZnxDft, a: &SvpPPol, b: &VecZnx);
227}
228
229impl SvpPPolOps for Module {
230    fn new_svp_ppol(&self) -> SvpPPol {
231        let mut data: Vec<u8> = alloc_aligned::<u8>(self.bytes_of_svp_ppol());
232        let ptr: *mut u8 = data.as_mut_ptr();
233        SvpPPol {
234            data: data,
235            ptr: ptr,
236            n: self.n(),
237            backend: self.backend(),
238        }
239    }
240
241    fn bytes_of_svp_ppol(&self) -> usize {
242        unsafe { svp::bytes_of_svp_ppol(self.ptr) as usize }
243    }
244
245    fn new_svp_ppol_from_bytes(&self, bytes: &mut [u8]) -> SvpPPol {
246        SvpPPol::from_bytes(self, bytes)
247    }
248
249    fn new_svp_ppol_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> SvpPPol {
250        SvpPPol::from_bytes_borrow(self, tmp_bytes)
251    }
252
253    fn svp_prepare(&self, svp_ppol: &mut SvpPPol, a: &Scalar) {
254        unsafe { svp::svp_prepare(self.ptr, svp_ppol.ptr as *mut svp_ppol_t, a.as_ptr()) }
255    }
256
257    fn svp_apply_dft(&self, c: &mut VecZnxDft, a: &SvpPPol, b: &VecZnx) {
258        unsafe {
259            svp::svp_apply_dft(
260                self.ptr,
261                c.ptr as *mut vec_znx_dft_t,
262                c.cols() as u64,
263                a.ptr as *const svp_ppol_t,
264                b.as_ptr(),
265                b.cols() as u64,
266                b.n() as u64,
267            )
268        }
269    }
270}