arnaucube
arnaucube/phantom-zonePublic Self-hosted repository
phantom-zone/src/decomposer.rs
src/decomposer.rsRaw
  1use itertools::{izip, Itertools};
  2use num_traits::{
  3    AsPrimitive, FromPrimitive, Num, One, PrimInt, ToPrimitive, WrappingAdd, WrappingSub, Zero,
  4};
  5use std::{
  6    fmt::{Debug, Display},
  7    marker::PhantomData,
  8    ops::Rem,
  9};
 10
 11use crate::backend::{ArithmeticOps, ModularOpsU64};
 12
 13fn gadget_vector<T: PrimInt>(logq: usize, logb: usize, d: usize) -> Vec<T> {
 14    assert!(logq >= (logb * d));
 15    let ignored_bits = logq - (logb * d);
 16
 17    (0..d)
 18        .into_iter()
 19        .map(|i| T::one() << (logb * i + ignored_bits))
 20        .collect_vec()
 21}
 22
 23pub trait RlweDecomposer {
 24    type Element;
 25    type D: Decomposer<Element = Self::Element>;
 26
 27    /// Decomposer for RLWE Part A
 28    fn a(&self) -> &Self::D;
 29    /// Decomposer for RLWE Part B
 30    fn b(&self) -> &Self::D;
 31}
 32
 33impl<D> RlweDecomposer for (D, D)
 34where
 35    D: Decomposer,
 36{
 37    type D = D;
 38    type Element = D::Element;
 39    fn a(&self) -> &Self::D {
 40        &self.0
 41    }
 42    fn b(&self) -> &Self::D {
 43        &self.1
 44    }
 45}
 46
 47pub trait Decomposer {
 48    type Element;
 49    type Iter: Iterator<Item = Self::Element>;
 50    fn new(q: Self::Element, logb: usize, d: usize) -> Self;
 51
 52    fn decompose_to_vec(&self, v: &Self::Element) -> Vec<Self::Element>;
 53    fn decompose_iter(&self, v: &Self::Element) -> Self::Iter;
 54    fn decomposition_count(&self) -> usize;
 55}
 56
 57pub struct DefaultDecomposer<T> {
 58    /// Ciphertext modulus
 59    q: T,
 60    /// Log of ciphertext modulus
 61    logq: usize,
 62    /// Log of base B
 63    logb: usize,
 64    /// base B
 65    b: T,
 66    /// (B - 1). To simulate (% B) as &(B-1), that is extract least significant
 67    /// logb bits
 68    b_mask: T,
 69    /// B/2
 70    bby2: T,
 71    /// Decomposition count
 72    d: usize,
 73    /// No. of bits to ignore in rounding
 74    ignore_bits: usize,
 75}
 76
 77pub trait NumInfo {
 78    const BITS: u32;
 79}
 80
 81impl NumInfo for u64 {
 82    const BITS: u32 = u64::BITS;
 83}
 84impl NumInfo for u32 {
 85    const BITS: u32 = u32::BITS;
 86}
 87impl NumInfo for u128 {
 88    const BITS: u32 = u128::BITS;
 89}
 90
 91impl<T: PrimInt + NumInfo + Debug> DefaultDecomposer<T> {
 92    fn recompose<Op>(&self, limbs: &[T], modq_op: &Op) -> T
 93    where
 94        Op: ArithmeticOps<Element = T>,
 95    {
 96        let mut value = T::zero();
 97        let gadget_vector = self.gadget_vector();
 98        assert!(limbs.len() == gadget_vector.len());
 99        izip!(limbs.iter(), gadget_vector.iter())
100            .for_each(|(d_el, beta)| value = modq_op.add(&value, &modq_op.mul(d_el, beta)));
101
102        value
103    }
104
105    pub(crate) fn gadget_vector(&self) -> Vec<T> {
106        return gadget_vector(self.logq, self.logb, self.d);
107    }
108}
109
110impl<
111        T: PrimInt
112            + ToPrimitive
113            + FromPrimitive
114            + WrappingSub
115            + WrappingAdd
116            + NumInfo
117            + From<bool>
118            + Display
119            + Debug,
120    > Decomposer for DefaultDecomposer<T>
121{
122    type Element = T;
123    type Iter = DecomposerIter<T>;
124
125    fn new(q: T, logb: usize, d: usize) -> DefaultDecomposer<T> {
126        // if q is power of 2, then `BITS - leading_zeros` outputs logq + 1.
127        let logq = if q & (q - T::one()) == T::zero() {
128            (T::BITS - q.leading_zeros() - 1) as usize
129        } else {
130            (T::BITS - q.leading_zeros()) as usize
131        };
132
133        assert!(
134            logq >= (logb * d),
135            "Decomposer wants logq >= logb*d but got logq={logq}, logb={logb}, d={d}"
136        );
137
138        let ignore_bits = logq - (logb * d);
139
140        DefaultDecomposer {
141            q,
142            logq,
143            logb,
144            b: T::one() << logb,
145            b_mask: (T::one() << logb) - T::one(),
146            bby2: T::one() << (logb - 1),
147            d,
148            ignore_bits,
149        }
150    }
151
152    // TODO(Jay): Outline the caveat
153    fn decompose_to_vec(&self, value: &T) -> Vec<T> {
154        let q = self.q;
155        let logb = self.logb;
156        let b = T::one() << logb;
157        let full_mask = b - T::one();
158        let bby2 = b >> 1;
159
160        let mut value = *value;
161        if value >= (q >> 1) {
162            value = !(q - value) + T::one()
163        }
164        value = round_value(value, self.ignore_bits);
165        let mut out = Vec::with_capacity(self.d);
166        for _ in 0..(self.d) {
167            let k_i = value & full_mask;
168
169            value = (value - k_i) >> logb;
170
171            if k_i > bby2 || (k_i == bby2 && ((value & T::one()) == T::one())) {
172                out.push(q - (b - k_i));
173                value = value + T::one();
174            } else {
175                out.push(k_i);
176            }
177        }
178
179        return out;
180    }
181
182    fn decomposition_count(&self) -> usize {
183        self.d
184    }
185
186    fn decompose_iter(&self, value: &T) -> DecomposerIter<T> {
187        let mut value = *value;
188        if value >= (self.q >> 1) {
189            value = !(self.q - value) + T::one()
190        }
191        value = round_value(value, self.ignore_bits);
192
193        DecomposerIter {
194            value,
195            q: self.q,
196            logq: self.logq,
197            logb: self.logb,
198            b: self.b,
199            bby2: self.bby2,
200            b_mask: self.b_mask,
201            steps_left: self.d,
202        }
203    }
204}
205
206impl<T: PrimInt> DefaultDecomposer<T> {}
207
208pub struct DecomposerIter<T> {
209    /// Value to decompose
210    value: T,
211    steps_left: usize,
212    /// (1 << logb) - 1 (for % (1<<logb); i.e. to extract least signiciant logb
213    /// bits)
214    b_mask: T,
215    logb: usize,
216    // b/2 = 1 << (logb-1)
217    bby2: T,
218    /// Ciphertext modulus
219    q: T,
220    /// Log of ciphertext modulus
221    logq: usize,
222    /// b = 1 << logb
223    b: T,
224}
225
226impl<T: PrimInt + From<bool> + WrappingSub + Display> Iterator for DecomposerIter<T> {
227    type Item = T;
228
229    fn next(&mut self) -> Option<Self::Item> {
230        if self.steps_left != 0 {
231            self.steps_left -= 1;
232            let k_i = self.value & self.b_mask;
233
234            self.value = (self.value - k_i) >> self.logb;
235
236            // if k_i > self.bby2 || (k_i == self.bby2 && ((self.value &
237            // T::one()) == T::one())) {     self.value = self.value
238            // + T::one();     Some(self.q + k_i - self.b)
239            // } else {
240            //     Some(k_i)
241            // }
242
243            // Following is without branching impl of the commented version above. It
244            // happens to speed up bootstrapping for `SMALL_MP_BOOL_PARAMS` (& other
245            // parameters as well but I haven't tested) by roughly 15ms.
246            // Suprisingly the improvement does not show up when I benchmark
247            // `decomposer_iter` in isolation. Putting this remark here as a
248            // future task to investiage (TODO).
249            let carry_bool =
250                k_i > self.bby2 || (k_i == self.bby2 && ((self.value & T::one()) == T::one()));
251            let carry = <T as From<bool>>::from(carry_bool);
252            let neg_carry = (T::zero().wrapping_sub(&carry));
253            self.value = self.value + carry;
254            Some((neg_carry & self.q) + k_i - (carry << self.logb))
255
256            // Some(
257            //     (self.q & ((carry << self.logq) - (T::one() & carry))) + k_i
258            // - (carry << self.logb), )
259
260            // Some(k_i)
261        } else {
262            None
263        }
264    }
265}
266
267fn round_value<T: PrimInt + WrappingAdd>(value: T, ignore_bits: usize) -> T {
268    if ignore_bits == 0 {
269        return value;
270    }
271
272    let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
273    (value >> ignore_bits).wrapping_add(&ignored_msb)
274}
275
276#[cfg(test)]
277mod tests {
278
279    use itertools::{izip, Itertools};
280    use rand::{thread_rng, Rng};
281
282    use crate::{
283        backend::{ModInit, ModularOpsU64, Modulus},
284        decomposer::round_value,
285        utils::{generate_prime, tests::Stats, TryConvertFrom1},
286    };
287
288    use super::{Decomposer, DefaultDecomposer};
289
290    #[test]
291    fn decomposition_works() {
292        let ring_size = 1 << 11;
293
294        let mut rng = thread_rng();
295
296        for logq in [37, 55] {
297            let logb = 11;
298            let d = 3;
299            let mut stats = vec![Stats::new(); d];
300
301            for i in [true] {
302                let q = if i {
303                    generate_prime(logq, 2 * ring_size, 1u64 << logq).unwrap()
304                } else {
305                    1u64 << logq
306                };
307                let decomposer = DefaultDecomposer::new(q, logb, d);
308                dbg!(decomposer.ignore_bits);
309                let modq_op = ModularOpsU64::new(q);
310                for _ in 0..1000000 {
311                    let value = rng.gen_range(0..q);
312                    let limbs = decomposer.decompose_to_vec(&value);
313                    let limbs_from_iter = decomposer.decompose_iter(&value).collect_vec();
314                    assert_eq!(limbs, limbs_from_iter);
315                    let value_back = round_value(
316                        decomposer.recompose(&limbs, &modq_op),
317                        decomposer.ignore_bits,
318                    );
319                    let rounded_value = round_value(value, decomposer.ignore_bits);
320                    assert!((rounded_value as i64 - value_back as i64).abs() <= 1,);
321
322                    izip!(stats.iter_mut(), limbs.iter()).for_each(|(s, l)| {
323                        s.add_more(&vec![q.map_element_to_i64(l)]);
324                    });
325                }
326            }
327
328            stats.iter().enumerate().for_each(|(index, s)| {
329                println!(
330                    "Limb {index} - Mean: {}, Std: {}",
331                    s.mean(),
332                    s.std_dev().abs().log2()
333                );
334            });
335        }
336    }
337}