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::{BACKEND, Module, VecZnx, VecZnxDft, assert_alignement};
  4
  5use crate::{Infos, alloc_aligned, cast_mut};
  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(self.ptr, self.n) }
 94    }
 95
 96    pub fn raw_mut(&self) -> &mut [i64] {
 97        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.n) }
 98    }
 99
100    pub fn fill_ternary_prob(&mut self, prob: f64, source: &mut Source) {
101        let choices: [i64; 3] = [-1, 0, 1];
102        let weights: [f64; 3] = [prob / 2.0, 1.0 - prob, prob / 2.0];
103        let dist: WeightedIndex<f64> = WeightedIndex::new(&weights).unwrap();
104        self.data
105            .iter_mut()
106            .for_each(|x: &mut i64| *x = choices[dist.sample(source)]);
107    }
108
109    pub fn fill_ternary_hw(&mut self, hw: usize, source: &mut Source) {
110        assert!(hw <= self.n());
111        self.data[..hw]
112            .iter_mut()
113            .for_each(|x: &mut i64| *x = (((source.next_u32() & 1) as i64) << 1) - 1);
114        self.data.shuffle(source);
115    }
116
117    pub fn as_vec_znx(&self) -> VecZnx {
118        VecZnx {
119            n: self.n,
120            cols: 1,
121            data: Vec::new(),
122            ptr: self.ptr,
123        }
124    }
125}
126
127pub trait ScalarOps {
128    fn bytes_of_scalar(&self) -> usize;
129    fn new_scalar(&self) -> Scalar;
130    fn new_scalar_from_bytes(&self, bytes: &mut [u8]) -> Scalar;
131    fn new_scalar_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> Scalar;
132}
133impl ScalarOps for Module {
134    fn bytes_of_scalar(&self) -> usize {
135        Scalar::bytes_of(self.n())
136    }
137    fn new_scalar(&self) -> Scalar {
138        Scalar::new(self.n())
139    }
140    fn new_scalar_from_bytes(&self, bytes: &mut [u8]) -> Scalar {
141        Scalar::from_bytes(self.n(), bytes)
142    }
143    fn new_scalar_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> Scalar {
144        Scalar::from_bytes_borrow(self.n(), tmp_bytes)
145    }
146}
147
148pub struct SvpPPol {
149    pub n: usize,
150    pub data: Vec<u8>,
151    pub ptr: *mut u8,
152    pub backend: BACKEND,
153}
154
155/// A prepared [crate::Scalar] for [SvpPPolOps::svp_apply_dft].
156/// An [SvpPPol] an be seen as a [VecZnxDft] of one limb.
157impl SvpPPol {
158    pub fn new(module: &Module) -> Self {
159        module.new_svp_ppol()
160    }
161
162    /// Returns the ring degree of the [SvpPPol].
163    pub fn n(&self) -> usize {
164        self.n
165    }
166
167    pub fn bytes_of(module: &Module) -> usize {
168        module.bytes_of_svp_ppol()
169    }
170
171    pub fn from_bytes(module: &Module, bytes: &mut [u8]) -> SvpPPol {
172        #[cfg(debug_assertions)]
173        {
174            assert_alignement(bytes.as_ptr());
175            assert_eq!(bytes.len(), module.bytes_of_svp_ppol());
176        }
177        unsafe {
178            Self {
179                n: module.n(),
180                data: Vec::from_raw_parts(bytes.as_mut_ptr(), bytes.len(), bytes.len()),
181                ptr: bytes.as_mut_ptr(),
182                backend: module.backend(),
183            }
184        }
185    }
186
187    pub fn from_bytes_borrow(module: &Module, tmp_bytes: &mut [u8]) -> SvpPPol {
188        #[cfg(debug_assertions)]
189        {
190            assert_alignement(tmp_bytes.as_ptr());
191            assert_eq!(tmp_bytes.len(), module.bytes_of_svp_ppol());
192        }
193        Self {
194            n: module.n(),
195            data: Vec::new(),
196            ptr: tmp_bytes.as_mut_ptr(),
197            backend: module.backend(),
198        }
199    }
200
201    /// Returns the number of cols of the [SvpPPol], which is always 1.
202    pub fn cols(&self) -> usize {
203        1
204    }
205}
206
207pub trait SvpPPolOps {
208    /// Allocates a new [SvpPPol].
209    fn new_svp_ppol(&self) -> SvpPPol;
210
211    /// Returns the minimum number of bytes necessary to allocate
212    /// a new [SvpPPol] through [SvpPPol::from_bytes] ro.
213    fn bytes_of_svp_ppol(&self) -> usize;
214
215    /// Allocates a new [SvpPPol] from an array of bytes.
216    /// The array of bytes is owned by the [SvpPPol].
217    /// The method will panic if bytes.len() < [SvpPPolOps::bytes_of_svp_ppol]
218    fn new_svp_ppol_from_bytes(&self, bytes: &mut [u8]) -> SvpPPol;
219
220    /// Allocates a new [SvpPPol] from an array of bytes.
221    /// The array of bytes is borrowed by the [SvpPPol].
222    /// The method will panic if bytes.len() < [SvpPPolOps::bytes_of_svp_ppol]
223    fn new_svp_ppol_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> SvpPPol;
224
225    /// Prepares a [crate::Scalar] for a [SvpPPolOps::svp_apply_dft].
226    fn svp_prepare(&self, svp_ppol: &mut SvpPPol, a: &Scalar);
227
228    /// Applies the [SvpPPol] x [VecZnxDft] product, where each limb of
229    /// the [VecZnxDft] is multiplied with [SvpPPol].
230    fn svp_apply_dft(&self, c: &mut VecZnxDft, a: &SvpPPol, b: &VecZnx);
231}
232
233impl SvpPPolOps for Module {
234    fn new_svp_ppol(&self) -> SvpPPol {
235        let mut data: Vec<u8> = alloc_aligned::<u8>(self.bytes_of_svp_ppol());
236        let ptr: *mut u8 = data.as_mut_ptr();
237        SvpPPol {
238            data: data,
239            ptr: ptr,
240            n: self.n(),
241            backend: self.backend(),
242        }
243    }
244
245    fn bytes_of_svp_ppol(&self) -> usize {
246        unsafe { svp::bytes_of_svp_ppol(self.ptr) as usize }
247    }
248
249    fn new_svp_ppol_from_bytes(&self, bytes: &mut [u8]) -> SvpPPol {
250        SvpPPol::from_bytes(self, bytes)
251    }
252
253    fn new_svp_ppol_from_bytes_borrow(&self, tmp_bytes: &mut [u8]) -> SvpPPol {
254        SvpPPol::from_bytes_borrow(self, tmp_bytes)
255    }
256
257    fn svp_prepare(&self, svp_ppol: &mut SvpPPol, a: &Scalar) {
258        unsafe { svp::svp_prepare(self.ptr, svp_ppol.ptr as *mut svp_ppol_t, a.as_ptr()) }
259    }
260
261    fn svp_apply_dft(&self, c: &mut VecZnxDft, a: &SvpPPol, b: &VecZnx) {
262        unsafe {
263            svp::svp_apply_dft(
264                self.ptr,
265                c.ptr as *mut vec_znx_dft_t,
266                c.cols() as u64,
267                a.ptr as *const svp_ppol_t,
268                b.as_ptr(),
269                b.cols() as u64,
270                b.n() as u64,
271            )
272        }
273    }
274}