tfhe 1.6.1

TFHE-rs is a fully homomorphic encryption (FHE) library that implements Zama's variant of TFHE.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
use super::ServerKey;
use crate::core_crypto::prelude::UnsignedInteger;
use crate::integer::ciphertext::boolean_value::BooleanBlock;
use crate::integer::ciphertext::IntegerRadixCiphertext;
use crate::integer::prelude::ServerKeyDefaultCMux;
use crate::shortint::{Ciphertext, MessageModulus};
use rayon::prelude::*;

#[derive(Debug, Copy, Clone)]
pub(crate) enum ComparisonKind {
    Less,
    LessOrEqual,
    Greater,
    GreaterOrEqual,
}

/// This blocks contains part of the information necessary to conclude, for signed ciphertext
/// it just needs some input borrow
///
/// There are 2 possibilities:
///
/// * If a block can encrypt at least 4 bits (carry + msg) then the block contains information that
///   will allow determining the result of x < y in one PBS
/// * Otherwise the information is split in 2 blocks and a cmux will be required later
pub(crate) enum PreparedSignedCheck {
    // The information could be coded on 1 block
    // because a block store at least 4 bits of information
    Unified(Ciphertext),
    // The information had to be split
    Split((Ciphertext, Ciphertext)),
}

/// Given the last block of 2 _signed_ numbers x and y, and a borrow (0 or 1)
///
/// returns whether x < y
pub(crate) fn is_x_less_than_y_given_input_borrow(
    last_x_block: u64,
    last_y_block: u64,
    borrow: u64,
    message_modulus: MessageModulus,
) -> u64 {
    let last_bit_pos = message_modulus.0.ilog2() - 1;

    let mask = (1 << last_bit_pos) - 1;
    let x_without_last_bit = last_x_block & mask;
    let y_without_last_bit = last_y_block & mask;

    let input_borrow_to_last_bit = x_without_last_bit < (y_without_last_bit + borrow);

    let result = last_x_block.wrapping_sub(last_y_block + borrow);

    let output_sign_bit = (result >> last_bit_pos) & 1;
    let output_borrow = last_x_block < (last_y_block + borrow);

    let overflow_flag = input_borrow_to_last_bit ^ output_borrow;

    output_sign_bit ^ u64::from(overflow_flag)
}

impl ServerKey {
    pub fn unchecked_eq_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        // Even though the corresponding function
        // may already exist in self.key
        // we generate our own lut to do fewer allocations
        // one for all the threads as opposed to one per thread
        let lut = self
            .key
            .generate_lookup_table_bivariate(|x, y| u64::from(x == y));
        let mut block_comparisons = lhs.blocks().to_vec();
        block_comparisons
            .par_iter_mut()
            .zip(rhs.blocks().par_iter())
            .for_each(|(lhs_block, rhs_block)| {
                self.key
                    .unchecked_apply_lookup_table_bivariate_assign(lhs_block, rhs_block, &lut);
            });

        let is_equal_result = self.are_all_comparisons_block_true(block_comparisons);

        BooleanBlock::new_unchecked(is_equal_result)
    }

    pub fn unchecked_ne_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        // Even though the corresponding function
        // may already exist in self.key
        // we generate our own lut to do fewer allocations
        // one for all the threads as opposed to one per thread
        let lut = self
            .key
            .generate_lookup_table_bivariate(|x, y| u64::from(x != y));
        let mut block_comparisons = lhs.blocks().to_vec();
        block_comparisons
            .par_iter_mut()
            .zip(rhs.blocks().par_iter())
            .for_each(|(lhs_block, rhs_block)| {
                self.key
                    .unchecked_apply_lookup_table_bivariate_assign(lhs_block, rhs_block, &lut);
            });

        let result = self.is_at_least_one_comparisons_block_true(block_comparisons);
        BooleanBlock::new_unchecked(result)
    }

    /// This implements all comparisons (<, <=, >, >=) for both signed and unsigned
    ///
    /// * inputs must have the same number of blocks
    /// * block carries of both inputs must be empty
    /// * carry modulus == message modulus
    fn compare<T>(&self, a: &T, b: &T, compare: ComparisonKind) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        assert_eq!(
            a.blocks().len(),
            b.blocks().len(),
            "lhs and rhs must have the same number of blocks"
        );

        assert!(a.block_carries_are_empty(), "Block carries must be empty");
        assert!(b.block_carries_are_empty(), "Block carries must be empty");
        assert_eq!(
            self.carry_modulus().0,
            self.message_modulus().0,
            "The carry modulus must be == to the message modulus"
        );

        if a.blocks().is_empty() {
            // We interpret empty as 0
            return match compare {
                ComparisonKind::Less | ComparisonKind::Greater => {
                    self.create_trivial_boolean_block(false)
                }
                ComparisonKind::LessOrEqual | ComparisonKind::GreaterOrEqual => {
                    self.create_trivial_boolean_block(true)
                }
            };
        }

        // We have that `a < b` <=> `does_sub_overflows(a, b)` and we know how to do this.
        // Now, to have other comparisons, we will re-express them as less than (`<`)
        // with some potential boolean negation
        //
        // Note that for signed ciphertext it's not the overflowing sub that is used,
        // but it's still something that is based on the subtraction
        //
        // For both signed and unsigned, a subtraction with borrow is used
        // (as opposed to adding the negation)
        let (lhs, rhs, invert_subtraction_result) = match compare {
            // The easiest case, nothing changes
            ComparisonKind::Less => (a, b, false),
            //     `a <= b`
            // <=> `not(b < a)`
            // <=> `not(does_sub_overflows(b, a))`
            ComparisonKind::LessOrEqual => (b, a, true),
            //     `a > b`
            // <=> `b < a`
            // <=> `does_sub_overflows(b, a)`
            ComparisonKind::Greater => (b, a, false),
            //     `a >= b`
            // <=> `b <= a`
            // <=> `not(a < b)`
            // <=> `not(does_sub_overflows(a, b))`
            ComparisonKind::GreaterOrEqual => (a, b, true),
        };

        // When there is only one block in both operands,
        // we can take a shortcut by using bivariate PBS.
        if a.blocks().len() == 1 {
            let lut = if T::IS_SIGNED {
                self.key.generate_lookup_table_bivariate(|x, y| {
                    u64::from(invert_subtraction_result)
                        ^ is_x_less_than_y_given_input_borrow(x, y, 0, self.message_modulus())
                })
            } else {
                self.key.generate_lookup_table_bivariate(|x, y| {
                    let overflowed = x < y;
                    u64::from(invert_subtraction_result ^ overflowed)
                })
            };
            let result = self.key.unchecked_apply_lookup_table_bivariate(
                &lhs.blocks()[0],
                &rhs.blocks()[0],
                &lut,
            );
            return BooleanBlock::new_unchecked(result);
        }

        let sub_blocks = lhs
            .blocks()
            .iter()
            .zip(rhs.blocks().iter())
            .map(|(lhs_b, rhs_b)| self.key.unchecked_sub(lhs_b, rhs_b))
            .collect::<Vec<_>>();

        let block_modulus = self.message_modulus().0 * self.carry_modulus().0;
        let num_bits_in_block = block_modulus.ilog2();
        let grouping_size = num_bits_in_block as usize;

        // We are going to group blocks and compute how each group propagates/generates a borrow
        //
        // Again, in unsigned representation the output borrow of the whole operation (i.e. the
        // borrow generated by the last group) tells us the result of the comparison. For signed
        // representation we need to XOR the overflow flag and the sign bit of the result.
        let block_states = {
            let message_modulus = self.message_modulus().0;

            let mut first_grouping_luts = vec![{
                let first_block_state_fn = |block| {
                    if block < message_modulus {
                        1 // Borrows
                    } else {
                        0 // Nothing
                    }
                };
                self.key.generate_lookup_table(first_block_state_fn)
            }];
            for i in 1..grouping_size {
                let state_fn = |block| {
                    #[allow(clippy::comparison_chain)]
                    let r = if block < message_modulus {
                        2 // Borrows
                    } else if block == message_modulus {
                        1 // Propagates a borrow
                    } else {
                        0 // Does not borrow
                    };

                    r << (i - 1)
                };
                first_grouping_luts.push(self.key.generate_lookup_table(state_fn));
            }

            let other_block_state_luts = (0..grouping_size)
                .map(|i| {
                    let state_fn = |block| {
                        #[allow(clippy::comparison_chain)]
                        let r = if block < message_modulus {
                            2 // Generates borrow
                        } else if block == message_modulus {
                            1 // Propagates a borrow
                        } else {
                            0 // Does not borrow
                        };

                        r << i
                    };
                    self.key.generate_lookup_table(state_fn)
                })
                .collect::<Vec<_>>();

            let block_states =
                // With unsigned ciphertexts as, overflow (i.e. does the last block needs to borrow)
                // directly translates to lhs < rhs we compute the blocks states for all the blocks
                //
                // For signed numbers, we need to do something more specific with the last block
                // thus, we don't compute the last block state
                sub_blocks[..sub_blocks.len() - usize::from(T::IS_SIGNED)]
                    .par_iter()
                    .enumerate()
                    .map(|(index, block)| {
                        let grouping_index = index / grouping_size;
                        let is_in_first_grouping = grouping_index == 0;
                        let index_in_grouping = index % (grouping_size);

                        let luts = if is_in_first_grouping {
                            &first_grouping_luts[index_in_grouping]
                        } else {
                            &other_block_state_luts[index_in_grouping]
                        };

                        self.key.apply_lookup_table(block, luts)
                    })
                    .collect::<Vec<_>>();

            block_states
        };

        // group borrows and simulator of last block
        let (
            (group_borrows, use_sequential_algorithm_to_resolve_grouping_carries),
            maybe_prepared_signed_check,
        ) = rayon::join(
            || {
                self.compute_group_borrow_state(
                    // May only invert if T is not signed
                    // As when there is only one group, in the unsigned case since overflow
                    // directly translate to lhs < rhs, we can ask the LUT used to do the
                    // inversion for us.
                    //
                    // In signed case as it's a bit more complex, we never want to
                    !T::IS_SIGNED && invert_subtraction_result,
                    grouping_size,
                    block_states,
                )
            },
            || {
                // When the ciphertexts are signed, finding whether lhs < rhs by doing a sub
                // is less direct than in unsigned where we can check for overflow.
                if T::IS_SIGNED && self.message_modulus().0 > 2 {
                    // Luckily, when the blocks have 4 bits, we can precompute and store in a block
                    // the 2 possible values for `lhs < rhs` depending on whether the last block
                    // will be borrowed from.
                    let lut = self.key.generate_lookup_table_bivariate(|x, y| {
                        let b0 =
                            is_x_less_than_y_given_input_borrow(x, y, 0, self.message_modulus());
                        let b1 =
                            is_x_less_than_y_given_input_borrow(x, y, 1, self.message_modulus());
                        ((b1 << 1) | b0) << 2
                    });

                    Some(PreparedSignedCheck::Unified(
                        self.key.apply_lookup_table_bivariate(
                            lhs.blocks().last().unwrap(),
                            rhs.blocks().last().unwrap(),
                            &lut,
                        ),
                    ))
                } else if T::IS_SIGNED {
                    Some(PreparedSignedCheck::Split(rayon::join(
                        || {
                            let lut = self.key.generate_lookup_table_bivariate(|x, y| {
                                is_x_less_than_y_given_input_borrow(x, y, 1, self.message_modulus())
                            });
                            self.key.apply_lookup_table_bivariate(
                                lhs.blocks().last().unwrap(),
                                rhs.blocks().last().unwrap(),
                                &lut,
                            )
                        },
                        || {
                            let lut = self.key.generate_lookup_table_bivariate(|x, y| {
                                is_x_less_than_y_given_input_borrow(x, y, 0, self.message_modulus())
                            });
                            self.key.apply_lookup_table_bivariate(
                                lhs.blocks().last().unwrap(),
                                rhs.blocks().last().unwrap(),
                                &lut,
                            )
                        },
                    )))
                } else {
                    None
                }
            },
        );

        self.finish_comparison(
            group_borrows,
            grouping_size,
            use_sequential_algorithm_to_resolve_grouping_carries,
            maybe_prepared_signed_check,
            invert_subtraction_result,
        )
    }

    pub(crate) fn finish_comparison(
        &self,
        mut group_borrows: Vec<Ciphertext>,
        grouping_size: usize,
        use_sequential_algorithm_to_resolve_grouping_carries: bool,
        maybe_prepared_signed_check: Option<PreparedSignedCheck>,
        invert_result: bool,
    ) -> BooleanBlock {
        let mut last_group_borrow_state = group_borrows.pop().unwrap();

        // Third step: resolving borrow propagation between the groups
        let resolved_borrows = if group_borrows.is_empty() {
            // There was only one group, and the borrow generated by this group
            // has already been added to the `overflow_block`, just earlier
            if maybe_prepared_signed_check.is_some() {
                // There is still one step to determine the result of the comparison
                // being done further down.
                // It will require an input borrow for the last group
                // which is 0 here because there was only one group thus,
                // the last group is the same as the first group,
                // and the input borrow of the first group is 0
                vec![]
            } else {
                // When unsigned, the result is already known at this point
                return BooleanBlock::new_unchecked(last_group_borrow_state);
            }
        } else if use_sequential_algorithm_to_resolve_grouping_carries {
            self.resolve_carries_of_groups_sequentially(group_borrows, grouping_size)
        } else {
            self.resolve_carries_of_groups_using_hillis_steele(group_borrows)
        };

        match maybe_prepared_signed_check {
            None => {
                // For unsigned numbers, if the last block borrows, then the subtraction
                // overflowed, which directly means lhs < rhs
                self.key.unchecked_add_assign(
                    &mut last_group_borrow_state,
                    // For unsigned, we know that if we are here,
                    // resolved_borrows is not empty
                    resolved_borrows.last().unwrap(),
                );
                let lut = self.key.generate_lookup_table(|block| {
                    let overflowed = (block >> 1) & 1;
                    u64::from(invert_result) ^ overflowed
                });

                self.key
                    .apply_lookup_table_assign(&mut last_group_borrow_state, &lut);

                BooleanBlock::new_unchecked(last_group_borrow_state)
            }
            Some(PreparedSignedCheck::Unified(ct)) => {
                // For signed numbers its less direct to do lhs < rhs using subtraction
                // fortunately when we have at least 4 bits we can encode all the needed information
                // in one block and conclude in 1 PBS
                if let Some(input_borrow) = resolved_borrows.last() {
                    self.key
                        .unchecked_add_assign(&mut last_group_borrow_state, input_borrow);
                }

                self.key
                    .unchecked_add_assign(&mut last_group_borrow_state, &ct);
                let lut = self.key.generate_lookup_table(|block| {
                    // The overflow block already contains the borrow,
                    // but the position of the borrow is one less bit further
                    let index = if resolved_borrows.is_empty() { 0 } else { 1 };
                    let input_borrow = (block >> index) & 1;

                    // Here, depending on the input borrow, we retrieve
                    // the bit that tells us if lhs < rhs
                    let r = if input_borrow == 1 {
                        (block >> 3) & 1
                    } else {
                        (block >> 2) & 1
                    };
                    u64::from(invert_result) ^ r
                });

                self.key
                    .apply_lookup_table_assign(&mut last_group_borrow_state, &lut);

                BooleanBlock::new_unchecked(last_group_borrow_state)
            }
            Some(PreparedSignedCheck::Split((if_input_borrow_is_1, if_input_borrow_is_0))) => {
                if let Some(input_borrow) = resolved_borrows.last() {
                    self.key
                        .unchecked_add_assign(&mut last_group_borrow_state, input_borrow);
                    let lut = self.key.generate_lookup_table(|x| (x >> 1) & 1);
                    self.key
                        .apply_lookup_table_assign(&mut last_group_borrow_state, &lut);
                }

                let if_input_borrow_is_1 = BooleanBlock::new_unchecked(if_input_borrow_is_1);
                let if_input_borrow_is_0 = BooleanBlock::new_unchecked(if_input_borrow_is_0);
                let condition = BooleanBlock::new_unchecked(last_group_borrow_state);
                let result = self.if_then_else_parallelized(
                    &condition,
                    &if_input_borrow_is_1,
                    &if_input_borrow_is_0,
                );
                if invert_result {
                    self.boolean_bitnot(&result)
                } else {
                    result
                }
            }
        }
    }

    /// The invert_result boolean is only used when there is one and only one group
    pub(crate) fn compute_group_borrow_state(
        &self,
        invert_result: bool,
        grouping_size: usize,
        block_states: Vec<Ciphertext>,
    ) -> (Vec<Ciphertext>, bool) {
        if block_states.len() == 1 {
            return (block_states, true);
        }

        let message_modulus = self.key.message_modulus.0;
        let block_modulus = message_modulus * self.carry_modulus().0;
        let num_bits_in_block = block_modulus.ilog2();
        let num_blocks = block_states.len();
        let num_groups = num_blocks.div_ceil(grouping_size);

        let num_groupings = num_blocks.div_ceil(grouping_size);
        let num_carry_to_resolve = num_groupings - 1;

        let sequential_depth = (num_carry_to_resolve as u32) / (grouping_size as u32 - 1);

        let hillis_steel_depth = if num_carry_to_resolve == 0 {
            0
        } else {
            num_carry_to_resolve.ceil_ilog2()
        };

        let use_sequential_algorithm_to_resolved_grouping_carries = if num_bits_in_block >= 4 {
            sequential_depth <= hillis_steel_depth
        } else {
            true // Hillis-Steele base propagation requires 4 bits
        };

        // This will be used only if there are at least 2 groups
        let first_group_propagation_lut = self
            .key
            .generate_lookup_table(|block| (block >> (num_bits_in_block as u64 - 1)) & 1);

        // This stores the LUTs that output the propagation result of the other groupings
        let grouping_chunk_pgn_luts = if use_sequential_algorithm_to_resolved_grouping_carries {
            // When using the sequential algorithm for the propagation of one grouping to the
            // other we need to shift the PGN state to the correct position, so we later, when
            // using them only lwe_add is needed and so noise management is easy
            //
            // Also, these LUTs are 'negacylic', they are made to exploit the padding bit
            // resulting blocks from these LUTs must be added the constant `1 << index`.
            (0..grouping_size - 1)
                .map(|i| {
                    self.key.generate_lookup_table(|block| {
                        // All bits set to 1 (e.g. 0b1111), means propagate
                        if block == (block_modulus - 1) {
                            0
                        } else {
                            // u64::MAX is -1 in two's complement
                            // We apply the modulus including the padding bit
                            (u64::MAX << i) % (1 << (num_bits_in_block + 1))
                        }
                    })
                })
                .collect::<Vec<_>>()
        } else {
            // This LUT is for when we are using Hillis-Steele prefix-scan to propagate carries
            // between groupings. When using this propagation, the encoding of the states
            // are a bit different.
            //
            // Also, these LUTs are 'negacylic', they are made to exploit the padding bit
            // resulting blocks from these LUTs must be added the constant `1`.
            vec![self.key.generate_lookup_table(|block| {
                if block == (block_modulus - 1) {
                    // All bits set to 1 (e.g. 0b1111), means propagate
                    2
                } else {
                    // u64::MAX is -1 in tow's complement
                    // We apply the modulus including the padding bit
                    u64::MAX % (block_modulus * 2)
                }
            })]
        };

        // The last group may not be full
        let mut num_blocks_in_last_group = block_states.len() % grouping_size;
        if num_blocks_in_last_group == 0 {
            num_blocks_in_last_group = grouping_size;
        }
        let (last_group_lut, last_group_lut_corrector) = if num_groups == 1 {
            // The last group is the only one
            let lut = self.key.generate_lookup_table(|cum_sum_block| {
                let index_of_last_block = num_blocks_in_last_group - 1;
                let overflowed = (cum_sum_block >> index_of_last_block) & 1;
                u64::from(invert_result) ^ overflowed
            });
            (lut, 0)
        } else {
            let may_have_its_padding_bit_set = num_blocks_in_last_group == grouping_size;
            if may_have_its_padding_bit_set {
                let lut = self.key.generate_lookup_table(|cum_sum_block| {
                    if cum_sum_block == (block_modulus - 1) {
                        0
                    } else {
                        // u64::MAX is -1 in tow's complement
                        // We apply the modulus including the padding bit
                        u64::MAX % (1 << (num_bits_in_block + 1))
                    }
                });
                (lut, 1)
            } else {
                let lut = self.key.generate_lookup_table(|cum_sum_block| {
                    let propagate_state = (1 << num_blocks_in_last_group) - 1;
                    #[allow(clippy::comparison_chain)]
                    if cum_sum_block > propagate_state {
                        2 // Generates
                    } else if cum_sum_block == propagate_state {
                        1 // Propagate
                    } else {
                        0
                    }
                });
                (lut, 0)
            }
        };

        // Stores for each group, the cum sum the block state of each of its member
        let group_propagation_state = block_states
            .par_chunks(grouping_size)
            .enumerate()
            .map(|(i, grouping)| {
                let mut result = grouping[0].clone();
                for other in &grouping[1..] {
                    self.key.unchecked_add_assign(&mut result, other);
                }

                // i == (num_groups - 1) takes precedence over
                // i == 0 as when num_groups -1 == 0, the correct lut to use is
                // the last group lut
                if i == num_groups - 1 {
                    self.key
                        .apply_lookup_table_assign(&mut result, &last_group_lut);
                    self.key
                        .unchecked_scalar_add_assign(&mut result, last_group_lut_corrector)
                } else if i == 0 {
                    self.key
                        .apply_lookup_table_assign(&mut result, &first_group_propagation_lut)
                } else {
                    let index = if use_sequential_algorithm_to_resolved_grouping_carries {
                        // Select the correct LUT so that the result
                        // is aligned to the correct position for sequential algorithm
                        // to work
                        (i - 1) % (grouping_size - 1)
                    } else {
                        0
                    };
                    self.key
                        .apply_lookup_table_assign(&mut result, &grouping_chunk_pgn_luts[index]);

                    let corrector = if use_sequential_algorithm_to_resolved_grouping_carries {
                        1 << ((i - 1) % (grouping_size - 1))
                    } else {
                        1
                    };
                    self.key.unchecked_scalar_add_assign(&mut result, corrector);
                    result.degree = crate::shortint::ciphertext::Degree::new(3);
                }

                result
            })
            .collect::<Vec<_>>();

        (
            group_propagation_state,
            use_sequential_algorithm_to_resolved_grouping_carries,
        )
    }

    pub fn unchecked_gt_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        self.compare(lhs, rhs, ComparisonKind::Greater)
    }

    pub fn unchecked_ge_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        self.compare(lhs, rhs, ComparisonKind::GreaterOrEqual)
    }

    pub fn unchecked_lt_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        self.compare(lhs, rhs, ComparisonKind::Less)
    }

    pub fn unchecked_le_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        self.compare(lhs, rhs, ComparisonKind::LessOrEqual)
    }

    pub fn unchecked_max_parallelized<T>(&self, lhs: &T, rhs: &T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let is_superior = self.unchecked_gt_parallelized(lhs, rhs);
        self.unchecked_if_then_else_parallelized(&is_superior, lhs, rhs)
    }

    pub fn unchecked_min_parallelized<T>(&self, lhs: &T, rhs: &T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let is_inferior = self.unchecked_lt_parallelized(lhs, rhs);
        self.unchecked_if_then_else_parallelized(&is_inferior, lhs, rhs)
    }

    pub fn smart_eq_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        rayon::join(
            || {
                if !lhs.block_carries_are_empty() {
                    self.full_propagate_parallelized(lhs);
                }
            },
            || {
                if !rhs.block_carries_are_empty() {
                    self.full_propagate_parallelized(rhs);
                }
            },
        );
        self.unchecked_eq_parallelized(lhs, rhs)
    }

    pub fn smart_ne_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        rayon::join(
            || {
                if !lhs.block_carries_are_empty() {
                    self.full_propagate_parallelized(lhs);
                }
            },
            || {
                if !rhs.block_carries_are_empty() {
                    self.full_propagate_parallelized(rhs);
                }
            },
        );
        self.unchecked_ne_parallelized(lhs, rhs)
    }

    pub fn smart_gt_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_gt_parallelized(lhs, rhs)
    }

    pub fn smart_ge_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_ge_parallelized(lhs, rhs)
    }

    pub fn smart_lt_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_lt_parallelized(lhs, rhs)
    }

    pub fn smart_le_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_le_parallelized(lhs, rhs)
    }

    pub fn smart_max_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_max_parallelized(lhs, rhs)
    }

    pub fn smart_min_parallelized<T>(&self, lhs: &mut T, rhs: &mut T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        if !lhs.block_carries_are_empty() {
            self.full_propagate_parallelized(lhs);
        }
        if !rhs.block_carries_are_empty() {
            self.full_propagate_parallelized(rhs);
        }
        self.unchecked_min_parallelized(lhs, rhs)
    }

    pub fn eq_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_eq_parallelized(lhs, rhs)
    }

    pub fn ne_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_ne_parallelized(lhs, rhs)
    }

    pub fn gt_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_gt_parallelized(lhs, rhs)
    }

    pub fn ge_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_ge_parallelized(lhs, rhs)
    }

    pub fn lt_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_lt_parallelized(lhs, rhs)
    }

    pub fn le_parallelized<T>(&self, lhs: &T, rhs: &T) -> BooleanBlock
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;
        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_le_parallelized(lhs, rhs)
    }

    pub fn max_parallelized<T>(&self, lhs: &T, rhs: &T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;

        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_max_parallelized(lhs, rhs)
    }

    pub fn min_parallelized<T>(&self, lhs: &T, rhs: &T) -> T
    where
        T: IntegerRadixCiphertext,
    {
        let mut tmp_lhs;
        let mut tmp_rhs;

        let (lhs, rhs) = match (lhs.block_carries_are_empty(), rhs.block_carries_are_empty()) {
            (true, true) => (lhs, rhs),
            (true, false) => {
                tmp_rhs = rhs.clone();
                self.full_propagate_parallelized(&mut tmp_rhs);
                (lhs, &tmp_rhs)
            }
            (false, true) => {
                tmp_lhs = lhs.clone();
                self.full_propagate_parallelized(&mut tmp_lhs);
                (&tmp_lhs, rhs)
            }
            (false, false) => {
                tmp_lhs = lhs.clone();
                tmp_rhs = rhs.clone();
                rayon::join(
                    || self.full_propagate_parallelized(&mut tmp_lhs),
                    || self.full_propagate_parallelized(&mut tmp_rhs),
                );
                (&tmp_lhs, &tmp_rhs)
            }
        };

        self.unchecked_min_parallelized(lhs, rhs)
    }
}