arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/poulpy-schemes/src/tfhe/blind_rotation/lut.rs
poulpy-schemes/src/tfhe/blind_rotation/lut.rsRaw
  1use poulpy_hal::{
  2    api::{
  3        ScratchOwnedAlloc, ScratchOwnedBorrow, VecZnxCopy, VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxRotateInplace,
  4        VecZnxRotateInplaceTmpBytes, VecZnxSwitchRing,
  5    },
  6    layouts::{Backend, Module, ScratchOwned, VecZnx, ZnxInfos, ZnxViewMut},
  7};
  8
  9#[derive(Debug, Clone, Copy)]
 10pub enum LookUpTableRotationDirection {
 11    Left,
 12    Right,
 13}
 14
 15pub struct LookUpTable {
 16    pub(crate) data: Vec<VecZnx<Vec<u8>>>,
 17    pub(crate) rot_dir: LookUpTableRotationDirection,
 18    pub(crate) basek: usize,
 19    pub(crate) k: usize,
 20    pub(crate) drift: usize,
 21}
 22
 23impl LookUpTable {
 24    pub fn alloc<B: Backend>(module: &Module<B>, basek: usize, k: usize, extension_factor: usize) -> Self {
 25        #[cfg(debug_assertions)]
 26        {
 27            assert!(
 28                extension_factor & (extension_factor - 1) == 0,
 29                "extension_factor must be a power of two but is: {}",
 30                extension_factor
 31            );
 32        }
 33        let size: usize = k.div_ceil(basek);
 34        let mut data: Vec<VecZnx<Vec<u8>>> = Vec::with_capacity(extension_factor);
 35        (0..extension_factor).for_each(|_| {
 36            data.push(VecZnx::alloc(module.n(), 1, size));
 37        });
 38        Self {
 39            data,
 40            basek,
 41            k,
 42            drift: 0,
 43            rot_dir: LookUpTableRotationDirection::Left,
 44        }
 45    }
 46
 47    pub fn log_extension_factor(&self) -> usize {
 48        (usize::BITS - (self.extension_factor() - 1).leading_zeros()) as _
 49    }
 50
 51    pub fn extension_factor(&self) -> usize {
 52        self.data.len()
 53    }
 54
 55    pub fn domain_size(&self) -> usize {
 56        self.data.len() * self.data[0].n()
 57    }
 58
 59    pub fn rotation_direction(&self) -> LookUpTableRotationDirection {
 60        self.rot_dir
 61    }
 62
 63    // By default X^{-dec(lwe)} is computed during the blind rotation.
 64    // Setting [reverse_rotation] to true will reverse the sign of
 65    // rotation of the LUT by instead evaluating X^{dec(lwe)} during
 66    // the blind rotation.
 67    pub fn set_rotation_direction(&mut self, rot_dir: LookUpTableRotationDirection) {
 68        self.rot_dir = rot_dir
 69    }
 70
 71    pub fn set<B: Backend>(&mut self, module: &Module<B>, f: &[i64], k: usize)
 72    where
 73        Module<B>: VecZnxRotateInplace<B>
 74            + VecZnxNormalizeInplace<B>
 75            + VecZnxNormalizeTmpBytes
 76            + VecZnxSwitchRing
 77            + VecZnxCopy
 78            + VecZnxRotateInplaceTmpBytes,
 79        ScratchOwned<B>: ScratchOwnedAlloc<B> + ScratchOwnedBorrow<B>,
 80    {
 81        assert!(f.len() <= module.n());
 82
 83        let basek: usize = self.basek;
 84
 85        let mut scratch: ScratchOwned<B> = ScratchOwned::alloc(module.vec_znx_normalize_tmp_bytes());
 86
 87        // Get the number minimum limb to store the message modulus
 88        let limbs: usize = k.div_ceil(basek);
 89
 90        #[cfg(debug_assertions)]
 91        {
 92            assert!(f.len() <= module.n());
 93            assert!(
 94                (max_bit_size(f) + (k % basek) as u32) < i64::BITS,
 95                "overflow: max(|f|) << (k%basek) > i64::BITS"
 96            );
 97            assert!(limbs <= self.data[0].size());
 98        }
 99
100        // Scaling factor
101        let mut scale = 1;
102        if !k.is_multiple_of(basek) {
103            scale <<= basek - (k % basek);
104        }
105
106        // #elements in lookup table
107        let f_len: usize = f.len();
108
109        // If LUT size > TakeScalarZnx
110        let domain_size: usize = self.domain_size();
111
112        let size: usize = self.k.div_ceil(self.basek);
113
114        // Equivalent to AUTO([f(0), -f(n-1), -f(n-2), ..., -f(1)], -1)
115        let mut lut_full: VecZnx<Vec<u8>> = VecZnx::alloc(domain_size, 1, size);
116
117        let lut_at: &mut [i64] = lut_full.at_mut(0, limbs - 1);
118
119        let step: usize = domain_size.div_round(f_len);
120
121        f.iter().enumerate().for_each(|(i, fi)| {
122            let start: usize = i * step;
123            let end: usize = start + step;
124            lut_at[start..end].fill(fi * scale);
125        });
126
127        let drift: usize = step >> 1;
128
129        // Rotates half the step to the left
130
131        if self.extension_factor() > 1 {
132            (0..self.extension_factor()).for_each(|i| {
133                module.vec_znx_switch_ring(&mut self.data[i], 0, &lut_full, 0);
134                if i < self.extension_factor() {
135                    module.vec_znx_rotate_inplace(-1, &mut lut_full, 0, scratch.borrow());
136                }
137            });
138        } else {
139            module.vec_znx_copy(&mut self.data[0], 0, &lut_full, 0);
140        }
141
142        self.data.iter_mut().for_each(|a| {
143            module.vec_znx_normalize_inplace(self.basek, a, 0, scratch.borrow());
144        });
145
146        self.rotate(module, -(drift as i64));
147
148        self.drift = drift
149    }
150
151    #[allow(dead_code)]
152    pub(crate) fn rotate<B: Backend>(&mut self, module: &Module<B>, k: i64)
153    where
154        Module<B>: VecZnxRotateInplace<B> + VecZnxRotateInplaceTmpBytes,
155        ScratchOwned<B>: ScratchOwnedAlloc<B> + ScratchOwnedBorrow<B>,
156    {
157        let extension_factor: usize = self.extension_factor();
158        let two_n: usize = 2 * self.data[0].n();
159        let two_n_ext: usize = two_n * extension_factor;
160
161        let mut scratch: ScratchOwned<_> = ScratchOwned::alloc(module.vec_znx_rotate_inplace_tmp_bytes());
162
163        let k_pos: usize = ((k + two_n_ext as i64) % two_n_ext as i64) as usize;
164
165        let k_hi: usize = k_pos / extension_factor;
166        let k_lo: usize = k_pos % extension_factor;
167
168        (0..extension_factor - k_lo).for_each(|i| {
169            module.vec_znx_rotate_inplace(k_hi as i64, &mut self.data[i], 0, scratch.borrow());
170        });
171
172        (extension_factor - k_lo..extension_factor).for_each(|i| {
173            module.vec_znx_rotate_inplace(k_hi as i64 + 1, &mut self.data[i], 0, scratch.borrow());
174        });
175
176        self.data.rotate_right(k_lo);
177    }
178}
179
180pub(crate) trait DivRound {
181    fn div_round(self, rhs: Self) -> Self;
182}
183
184impl DivRound for usize {
185    #[inline]
186    fn div_round(self, rhs: Self) -> Self {
187        (self + rhs / 2) / rhs
188    }
189}
190
191#[allow(dead_code)]
192fn max_bit_size(vec: &[i64]) -> u32 {
193    vec.iter()
194        .map(|&v| {
195            if v == 0 {
196                0
197            } else {
198                v.unsigned_abs().ilog2() + 1
199            }
200        })
201        .max()
202        .unwrap_or(0)
203}