tfhe 1.6.0

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
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
use crate::core_crypto::entities::packed_integers::PackedIntegers;
use crate::core_crypto::gpu::vec::{CudaVec, GpuIndex};
use crate::core_crypto::gpu::CudaStreams;
use crate::core_crypto::prelude::compressed_modulus_switched_glwe_ciphertext::CompressedModulusSwitchedGlweCiphertext;
use crate::core_crypto::prelude::LweCiphertextCount;
use crate::integer::ciphertext::{CompressedCiphertextList, DataKind};
use crate::integer::gpu::ciphertext::boolean_value::CudaBooleanBlock;
use crate::integer::gpu::ciphertext::{
    CudaIntegerRadixCiphertext, CudaRadixCiphertext, CudaSignedRadixCiphertext,
    CudaUnsignedRadixCiphertext,
};
use crate::integer::gpu::list_compression::server_keys::{
    CudaCompressionKey, CudaDecompressionKey, CudaPackedGlweCiphertextList,
    CudaPackedGlweCiphertextListMeta,
};
use crate::shortint::ciphertext::{
    CompressedCiphertextList as ShortintCompressedCiphertextList, CompressedCiphertextListMeta,
};
use crate::shortint::parameters::AtomicPatternKind;
use crate::shortint::PBSOrder;
use itertools::Itertools;
use serde::{Deserializer, Serializer};
use std::num::NonZeroUsize;

pub trait CudaExpandable: Sized {
    fn from_expanded_blocks(blocks: CudaRadixCiphertext, kind: DataKind) -> crate::Result<Self>;
}

impl<T> CudaExpandable for T
where
    T: CudaIntegerRadixCiphertext,
{
    fn from_expanded_blocks(blocks: CudaRadixCiphertext, kind: DataKind) -> crate::Result<Self> {
        match (kind, T::IS_SIGNED) {
            (DataKind::Unsigned(_), false) | (DataKind::Signed(_), true) => Ok(T::from(blocks)),
            (DataKind::Boolean, _) => {
                let signed_or_unsigned_str = if T::IS_SIGNED { "signed" } else { "unsigned" };
                Err(crate::Error::new(format!(
                    "Tried to expand a {signed_or_unsigned_str} radix while boolean is stored"
                )))
            }
            (DataKind::Unsigned(_), true) => Err(crate::Error::new(
                "Tried to expand a signed radix while an unsigned radix is stored".to_string(),
            )),
            (DataKind::Signed(_), false) => Err(crate::Error::new(
                "Tried to expand an unsigned radix while a signed radix is stored".to_string(),
            )),
            (DataKind::String { .. }, signed) => {
                let signedness = if signed { "signed" } else { "unsigned" };
                Err(crate::error!(
                    "Tried to expand a {signedness} radix while a string is stored"
                ))
            }
        }
    }
}

impl CudaExpandable for CudaBooleanBlock {
    fn from_expanded_blocks(blocks: CudaRadixCiphertext, kind: DataKind) -> crate::Result<Self> {
        match kind {
            DataKind::Unsigned(_) => Err(crate::Error::new(
                "Tried to expand a boolean block while an unsigned radix was stored".to_string(),
            )),
            DataKind::Signed(_) => Err(crate::Error::new(
                "Tried to expand a boolean block while a signed radix was stored".to_string(),
            )),
            DataKind::Boolean => Ok(Self::from_cuda_radix_ciphertext(blocks)),
            DataKind::String { .. } => Err(crate::Error::new(
                "Tried to expand a boolean block while a string  radix was stored".to_string(),
            )),
        }
    }
}
pub struct CudaCompressedCiphertextList {
    pub(crate) packed_list: CudaPackedGlweCiphertextList<u64>,
    pub(crate) info: Vec<DataKind>,
}

impl CudaCompressedCiphertextList {
    pub fn gpu_indexes(&self) -> &[GpuIndex] {
        &self.packed_list.data.gpu_indexes
    }
    pub fn len(&self) -> usize {
        self.info.len()
    }

    pub fn is_empty(&self) -> bool {
        self.info.len() == 0
    }

    pub fn get_kind_of(&self, index: usize) -> Option<DataKind> {
        self.info.get(index).copied()
    }

    #[allow(clippy::unnecessary_wraps)]
    fn blocks_of(
        &self,
        index: usize,
        decomp_key: &CudaDecompressionKey,
        streams: &CudaStreams,
    ) -> Option<(CudaRadixCiphertext, DataKind)> {
        let preceding_infos = self.info.get(..index)?;
        let current_info = self.info.get(index).copied()?;
        let message_modulus = self.packed_list.message_modulus()?;

        let start_block_index: usize = preceding_infos
            .iter()
            .copied()
            .map(|kind| kind.num_blocks(message_modulus))
            .sum();

        let end_block_index = start_block_index + current_info.num_blocks(message_modulus) - 1;

        Some((
            decomp_key
                .unpack(
                    &self.packed_list,
                    current_info,
                    start_block_index,
                    end_block_index,
                    streams,
                )
                .unwrap(),
            current_info,
        ))
    }

    fn get_blocks_of_size_on_gpu(
        &self,
        index: usize,
        decomp_key: &CudaDecompressionKey,
        streams: &CudaStreams,
    ) -> Option<u64> {
        let preceding_infos = self.info.get(..index)?;
        let current_info = self.info.get(index).copied()?;
        let message_modulus = self.packed_list.message_modulus()?;

        let start_block_index: usize = preceding_infos
            .iter()
            .copied()
            .map(|kind| kind.num_blocks(message_modulus))
            .sum();

        let end_block_index = start_block_index + current_info.num_blocks(message_modulus) - 1;

        Some(decomp_key.get_gpu_list_unpack_size_on_gpu(
            &self.packed_list,
            start_block_index,
            end_block_index,
            streams,
        ))
    }

    pub fn get<T>(
        &self,
        index: usize,
        decomp_key: &CudaDecompressionKey,
        streams: &CudaStreams,
    ) -> crate::Result<Option<T>>
    where
        T: CudaExpandable,
    {
        self.blocks_of(index, decomp_key, streams)
            .map(|(blocks, kind)| T::from_expanded_blocks(blocks, kind))
            .transpose()
    }

    pub fn get_decompression_size_on_gpu(
        &self,
        index: usize,
        decomp_key: &CudaDecompressionKey,
        streams: &CudaStreams,
    ) -> Option<u64> {
        self.get_blocks_of_size_on_gpu(index, decomp_key, streams)
    }

    /// ```rust
    ///  use tfhe::core_crypto::gpu::CudaStreams;
    /// use tfhe::integer::gpu::ciphertext::boolean_value::CudaBooleanBlock;
    /// use tfhe::integer::gpu::ciphertext::compressed_ciphertext_list::CudaCompressedCiphertextListBuilder;
    /// use tfhe::integer::gpu::ciphertext::{CudaSignedRadixCiphertext, CudaUnsignedRadixCiphertext};
    /// use tfhe::integer::gpu::gen_keys_radix_gpu;
    /// use tfhe::shortint::parameters::{
    ///     PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    ///     COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128
    /// };
    ///
    /// let block_params = PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    /// let compression_params = COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    /// let num_blocks = 32;
    /// let streams = CudaStreams::new_multi_gpu();
    ///
    /// let (radix_cks, _) = gen_keys_radix_gpu(block_params,
    ///     num_blocks,
    ///     &streams,
    /// );
    /// let cks = radix_cks.as_ref();
    ///
    /// let private_compression_key =
    /// cks.new_compression_private_key(compression_params);
    ///
    /// let (cuda_compression_key, cuda_decompression_key) =
    /// radix_cks.new_cuda_compression_decompression_keys(&private_compression_key, &streams);
    ///
    /// let private_compression_key =
    ///     cks.new_compression_private_key(compression_params);
    ///
    /// let (compressed_compression_key, compressed_decompression_key) =
    ///     radix_cks.new_compressed_compression_decompression_keys(&private_compression_key);
    ///
    /// let cuda_compression_key = compressed_compression_key.decompress_to_cuda(&streams);
    ///
    /// let compression_key = compressed_compression_key.decompress();
    /// let decompression_key = compressed_decompression_key.decompress();
    ///
    /// let ct1 = radix_cks.encrypt(3_u32);
    /// let ct2 = radix_cks.encrypt_signed(-2);
    /// let ct3 = radix_cks.encrypt_bool(true);
    ///
    /// // Copy to GPU
    /// let d_ct1 = CudaUnsignedRadixCiphertext::from_radix_ciphertext(&ct1, &streams);
    /// let d_ct2 = CudaSignedRadixCiphertext::from_signed_radix_ciphertext(&ct2, &streams);
    /// let d_ct3 = CudaBooleanBlock::from_boolean_block(&ct3, &streams);
    ///
    /// let cuda_compressed = CudaCompressedCiphertextListBuilder::new()
    ///     .push(d_ct1, &streams)
    ///     .push(d_ct2, &streams)
    ///     .push(d_ct3, &streams)
    ///     .build(&cuda_compression_key, &streams);
    ///
    /// let converted_compressed = cuda_compressed.to_compressed_ciphertext_list(&streams);
    /// ```
    pub fn to_compressed_ciphertext_list(&self, streams: &CudaStreams) -> CompressedCiphertextList {
        let Some(gpu_meta) = self.packed_list.meta.as_ref() else {
            // If there is no metadata, the list is empty
            let packed_list = ShortintCompressedCiphertextList {
                modulus_switched_glwe_ciphertext_list: Vec::new(),
                meta: None,
            };

            return CompressedCiphertextList {
                packed_list,
                info: Vec::new(),
            };
        };

        let ciphertext_modulus = gpu_meta.ciphertext_modulus;
        let message_modulus = gpu_meta.message_modulus;
        let carry_modulus = gpu_meta.carry_modulus;
        let lwe_per_glwe = gpu_meta.lwe_per_glwe;
        let storage_log_modulus = gpu_meta.storage_log_modulus;
        let glwe_dimension = gpu_meta.glwe_dimension;
        let polynomial_size = gpu_meta.polynomial_size;
        let mut modulus_switched_glwe_ciphertext_list =
            Vec::with_capacity(self.packed_list.glwe_ciphertext_count().0);

        let flat_cpu_data = unsafe {
            let mut v = vec![0u64; self.packed_list.data.len()];
            self.packed_list.data.copy_to_cpu_async(&mut v, streams, 0);
            streams.synchronize();
            v
        };

        let mut num_bodies_left = gpu_meta.total_lwe_bodies_count;
        let mut chunk_start = 0;
        while num_bodies_left != 0 {
            let bodies_count = LweCiphertextCount(num_bodies_left.min(lwe_per_glwe.0));
            let initial_len = (glwe_dimension.0 * polynomial_size.0) + bodies_count.0;
            let number_bits_to_pack = initial_len * storage_log_modulus.0;
            let len = number_bits_to_pack.div_ceil(u64::BITS as usize);
            let chunk_end = chunk_start + len;
            modulus_switched_glwe_ciphertext_list.push(
                CompressedModulusSwitchedGlweCiphertext::from_raw_parts(
                    PackedIntegers::from_raw_parts(
                        flat_cpu_data[chunk_start..chunk_end].to_vec(),
                        storage_log_modulus,
                        initial_len,
                    ),
                    glwe_dimension,
                    polynomial_size,
                    bodies_count,
                    ciphertext_modulus,
                ),
            );
            num_bodies_left = num_bodies_left.saturating_sub(lwe_per_glwe.0);
            chunk_start = chunk_end;
        }

        let atomic_pattern = AtomicPatternKind::Standard(PBSOrder::KeyswitchBootstrap);
        let meta = Some(CompressedCiphertextListMeta {
            ciphertext_modulus,
            message_modulus,
            carry_modulus,
            atomic_pattern,
            lwe_per_glwe,
        });
        let packed_list = ShortintCompressedCiphertextList {
            modulus_switched_glwe_ciphertext_list,
            meta,
        };

        CompressedCiphertextList {
            packed_list,
            info: self.info.clone(),
        }
    }

    pub fn duplicate(&self, streams: &CudaStreams) -> Self {
        Self {
            packed_list: self.packed_list.duplicate(streams),
            info: self.info.clone(),
        }
    }
}

impl CompressedCiphertextList {
    ///```rust
    /// use tfhe::core_crypto::gpu::CudaStreams;
    /// use tfhe::integer::ciphertext::CompressedCiphertextListBuilder;
    /// use tfhe::integer::gpu::ciphertext::boolean_value::CudaBooleanBlock;
    /// use tfhe::integer::gpu::ciphertext::{CudaSignedRadixCiphertext, CudaUnsignedRadixCiphertext};
    /// use tfhe::integer::gpu::gen_keys_radix_gpu;
    /// use tfhe::shortint::parameters::{
    ///     COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    ///     PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    /// };
    ///
    /// let block_params = PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    /// let compression_params =
    ///     COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    /// let num_blocks = 32;
    /// let streams = CudaStreams::new_multi_gpu();
    ///
    /// let (radix_cks, _) = gen_keys_radix_gpu(block_params, num_blocks, &streams);
    /// let cks = radix_cks.as_ref();
    ///
    /// let private_compression_key = cks.new_compression_private_key(compression_params);
    ///
    /// let (compressed_compression_key, compressed_decompression_key) =
    ///     radix_cks.new_compressed_compression_decompression_keys(&private_compression_key);
    ///
    /// let cuda_decompression_key = compressed_decompression_key.decompress_to_cuda(
    ///     radix_cks.parameters().glwe_dimension(),
    ///     radix_cks.parameters().polynomial_size(),
    ///     radix_cks.parameters().message_modulus(),
    ///     radix_cks.parameters().carry_modulus(),
    ///     radix_cks.parameters().ciphertext_modulus(),
    ///     &streams,
    /// );
    ///
    /// let compression_key = compressed_compression_key.decompress();
    ///
    /// let ct1 = radix_cks.encrypt(3_u32);
    /// let ct2 = radix_cks.encrypt_signed(-2);
    /// let ct3 = radix_cks.encrypt_bool(true);
    ///
    /// let compressed = CompressedCiphertextListBuilder::new()
    ///     .push(ct1)
    ///     .push(ct2)
    ///     .push(ct3)
    ///     .build(&compression_key);
    ///
    /// let cuda_compressed = compressed.to_cuda_compressed_ciphertext_list(&streams);
    /// let recovered_cuda_compressed = cuda_compressed.to_compressed_ciphertext_list(&streams);
    ///
    /// assert_eq!(recovered_cuda_compressed, compressed);
    ///
    /// let d_decompressed1: CudaUnsignedRadixCiphertext = cuda_compressed
    ///     .get(0, &cuda_decompression_key, &streams)
    ///     .unwrap()
    ///     .unwrap();
    /// let decompressed1 = d_decompressed1.to_radix_ciphertext(&streams);
    /// let decrypted: u32 = radix_cks.decrypt(&decompressed1);
    /// assert_eq!(decrypted, 3_u32);
    ///
    /// let d_decompressed2: CudaSignedRadixCiphertext = cuda_compressed
    ///     .get(1, &cuda_decompression_key, &streams)
    ///     .unwrap()
    ///     .unwrap();
    /// let decompressed2 = d_decompressed2.to_signed_radix_ciphertext(&streams);
    /// let decrypted: i32 = radix_cks.decrypt_signed(&decompressed2);
    /// assert_eq!(decrypted, -2);
    ///
    /// let d_decompressed3: CudaBooleanBlock = cuda_compressed
    ///     .get(2, &cuda_decompression_key, &streams)
    ///     .unwrap()
    ///     .unwrap();
    /// let decompressed3 = d_decompressed3.to_boolean_block(&streams);
    /// let decrypted = radix_cks.decrypt_bool(&decompressed3);
    /// assert!(decrypted);
    /// ```
    pub fn to_cuda_compressed_ciphertext_list(
        &self,
        streams: &CudaStreams,
    ) -> CudaCompressedCiphertextList {
        let modulus_switched_glwe_ciphertext_list =
            &self.packed_list.modulus_switched_glwe_ciphertext_list;

        let flat_cpu_data = modulus_switched_glwe_ciphertext_list
            .iter()
            .flat_map(|ct| ct.packed_integers().packed_coeffs().to_vec())
            .collect_vec();

        let flat_gpu_data = unsafe {
            let v = CudaVec::from_cpu_async(flat_cpu_data.as_slice(), streams, 0);
            streams.synchronize();
            v
        };

        let initial_len = modulus_switched_glwe_ciphertext_list
            .iter()
            .map(|glwe| glwe.packed_integers().initial_len())
            .sum();

        let meta = self.packed_list.meta.as_ref().and_then(|cpu_meta| {
            let lwe_per_glwe = cpu_meta.lwe_per_glwe;
            let message_modulus = cpu_meta.message_modulus;
            let carry_modulus = cpu_meta.carry_modulus;

            modulus_switched_glwe_ciphertext_list
                .first()
                .map(|first_ct| CudaPackedGlweCiphertextListMeta {
                    glwe_dimension: first_ct.glwe_dimension(),
                    polynomial_size: first_ct.polynomial_size(),
                    message_modulus,
                    carry_modulus,
                    ciphertext_modulus: cpu_meta.ciphertext_modulus,
                    storage_log_modulus: first_ct.packed_integers().log_modulus(),
                    lwe_per_glwe,
                    total_lwe_bodies_count: self.packed_list.len(),
                    initial_len,
                })
        });

        CudaCompressedCiphertextList {
            packed_list: CudaPackedGlweCiphertextList {
                data: flat_gpu_data,
                meta,
            },
            info: self.info.clone(),
        }
    }
}

pub trait CudaCompressible {
    fn compress_into(
        self,
        messages: &mut Vec<CudaRadixCiphertext>,
        streams: &CudaStreams,
    ) -> Option<DataKind>;
}

impl CudaCompressible for CudaSignedRadixCiphertext {
    fn compress_into(
        self,
        messages: &mut Vec<CudaRadixCiphertext>,
        streams: &CudaStreams,
    ) -> Option<DataKind> {
        let x = self.ciphertext.duplicate(streams);
        let num_blocks = x.d_blocks.lwe_ciphertext_count().0;

        let num_blocks = NonZeroUsize::new(num_blocks);
        if num_blocks.is_some() {
            messages.push(x)
        }
        num_blocks.map(DataKind::Signed)
    }
}

impl CudaCompressible for CudaBooleanBlock {
    fn compress_into(
        self,
        messages: &mut Vec<CudaRadixCiphertext>,
        streams: &CudaStreams,
    ) -> Option<DataKind> {
        let x = self.0.ciphertext.duplicate(streams);

        messages.push(x);
        Some(DataKind::Boolean)
    }
}
impl CudaCompressible for CudaUnsignedRadixCiphertext {
    fn compress_into(
        self,
        messages: &mut Vec<CudaRadixCiphertext>,
        streams: &CudaStreams,
    ) -> Option<DataKind> {
        let x = self.ciphertext.duplicate(streams);
        let num_blocks = x.d_blocks.lwe_ciphertext_count().0;

        let num_blocks = NonZeroUsize::new(num_blocks);
        if num_blocks.is_some() {
            messages.push(x)
        }
        num_blocks.map(DataKind::Unsigned)
    }
}

pub struct CudaCompressedCiphertextListBuilder {
    pub(crate) ciphertexts: Vec<CudaRadixCiphertext>,
    pub(crate) info: Vec<DataKind>,
}

impl CudaCompressedCiphertextListBuilder {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            ciphertexts: vec![],
            info: vec![],
        }
    }

    pub fn push<T: CudaCompressible>(&mut self, data: T, streams: &CudaStreams) -> &mut Self {
        if let Some(kind) = data.compress_into(&mut self.ciphertexts, streams) {
            self.info.push(kind);
        }
        self
    }

    pub fn extend<T>(&mut self, values: impl Iterator<Item = T>, streams: &CudaStreams) -> &mut Self
    where
        T: CudaCompressible,
    {
        for value in values {
            self.push(value, streams);
        }
        self
    }

    pub fn build(
        &self,
        comp_key: &CudaCompressionKey,
        streams: &CudaStreams,
    ) -> CudaCompressedCiphertextList {
        let packed_list = comp_key.compress_ciphertexts_into_list(&self.ciphertexts, streams);
        CudaCompressedCiphertextList {
            packed_list,
            info: self.info.clone(),
        }
    }
}

impl Clone for CudaCompressedCiphertextList {
    fn clone(&self) -> Self {
        Self {
            packed_list: self.packed_list.clone(),
            info: self.info.clone(),
        }
    }
}

impl serde::Serialize for CudaCompressedCiphertextList {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let streams = CudaStreams::new_multi_gpu();
        let cpu_res = self.to_compressed_ciphertext_list(&streams);
        cpu_res.serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for CudaCompressedCiphertextList {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let cpu_compressed = CompressedCiphertextList::deserialize(deserializer)?;
        let streams = CudaStreams::new_multi_gpu();

        Ok(cpu_compressed.to_cuda_compressed_ciphertext_list(&streams))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::integer::ciphertext::CompressedCiphertextListBuilder;
    use crate::integer::gpu::gen_keys_radix_gpu;
    use crate::integer::{ClientKey, RadixCiphertext, RadixClientKey};
    use crate::shortint::parameters::*;
    use crate::shortint::ShortintParameterSet;
    use rand::Rng;

    const NB_TESTS: usize = 10;
    const NB_OPERATOR_TESTS: usize = 10;

    #[test]
    fn test_cpu_to_gpu_compressed_ciphertext_list() {
        const NUM_BLOCKS: usize = 32;
        let streams = CudaStreams::new_multi_gpu();

        let params = PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        let comp_params = COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;

        let cks = ClientKey::new(params);

        let private_compression_key = cks.new_compression_private_key(comp_params);
        let (compressed_compression_key, compressed_decompression_key) =
            cks.new_compressed_compression_decompression_keys(&private_compression_key);
        let cuda_compression_key = compressed_compression_key.decompress_to_cuda(&streams);
        let cuda_decompression_key = compressed_decompression_key.decompress_to_cuda(
            cks.parameters().glwe_dimension(),
            cks.parameters().polynomial_size(),
            cks.parameters().message_modulus(),
            cks.parameters().carry_modulus(),
            cks.parameters().ciphertext_modulus(),
            &streams,
        );
        let cpu_compression_key = compressed_compression_key.decompress();
        let cpu_decompression_key = compressed_decompression_key.decompress();

        let radix_cks = RadixClientKey::from((cks, NUM_BLOCKS));

        // How many uints of NUM_BLOCKS we have to push in the list to ensure it
        // internally has more than one packed GLWE
        let max_nb_messages: usize = 1 + 2 * comp_params.lwe_per_glwe().0 / NUM_BLOCKS;

        let mut rng = rand::thread_rng();
        let message_modulus: u128 = radix_cks.parameters().message_modulus().0 as u128;
        let modulus = message_modulus.pow(NUM_BLOCKS as u32);
        let messages = (0..max_nb_messages)
            .map(|_| rng.gen::<u128>() % modulus)
            .collect::<Vec<_>>();

        let cpu_cts = messages
            .iter()
            .map(|message| radix_cks.encrypt(*message))
            .collect_vec();

        let cuda_cts = cpu_cts
            .iter()
            .map(|ct| CudaUnsignedRadixCiphertext::from_radix_ciphertext(ct, &streams))
            .collect_vec();

        let cpu_compressed_list = {
            let mut builder = CompressedCiphertextListBuilder::new();
            for d_ct in cpu_cts {
                builder.push(d_ct);
            }
            builder.build(&cpu_compression_key)
        };

        let cuda_compressed_list = {
            let mut builder = CudaCompressedCiphertextListBuilder::new();
            for d_ct in cuda_cts {
                builder.push(d_ct, &streams);
            }
            builder.build(&cuda_compression_key, &streams)
        };

        // Test Decompression on Gpu
        {
            // Roundtrip Gpu->Cpu->Gpu
            let cuda_compressed_list = cuda_compressed_list
                .to_compressed_ciphertext_list(&streams)
                .to_cuda_compressed_ciphertext_list(&streams);

            let cuda_compressed_list_2 =
                cpu_compressed_list.to_cuda_compressed_ciphertext_list(&streams);

            for (i, message) in messages.iter().enumerate() {
                let d_decompressed: CudaUnsignedRadixCiphertext = cuda_compressed_list
                    .get(i, &cuda_decompression_key, &streams)
                    .unwrap()
                    .unwrap();
                let decompressed = d_decompressed.to_radix_ciphertext(&streams);
                let decrypted: u128 = radix_cks.decrypt(&decompressed);
                assert_eq!(
                    decrypted, *message,
                    "Invalid decompression for cuda list that roundtripped Cuda->Cpu->Cuda"
                );

                let d_decompressed: CudaUnsignedRadixCiphertext = cuda_compressed_list_2
                    .get(i, &cuda_decompression_key, &streams)
                    .unwrap()
                    .unwrap();
                let decompressed = d_decompressed.to_radix_ciphertext(&streams);
                let decrypted: u128 = radix_cks.decrypt(&decompressed);
                assert_eq!(
                    decrypted, *message,
                    "Invalid decompression for cuda list that originated from Cpu"
                );
            }
        }

        // Test Decompression on CPU (to test conversions)
        {
            let expected_flat_len = cpu_compressed_list.packed_list.flat_len();

            // Roundtrip Cpu->Gpu->Cpu
            let cpu_compressed_list = cpu_compressed_list
                .to_cuda_compressed_ciphertext_list(&streams)
                .to_compressed_ciphertext_list(&streams);
            assert_eq!(
                cpu_compressed_list.packed_list.flat_len(),
                expected_flat_len,
                "Invalid flat len after Cpu->Gpu->Cpu"
            );

            let cpu_compressed_list_2 =
                cuda_compressed_list.to_compressed_ciphertext_list(&streams);
            assert_eq!(
                cpu_compressed_list_2.packed_list.flat_len(),
                expected_flat_len,
                "Invalid flat len after Gpu->Cpu"
            );

            for (i, message) in messages.iter().enumerate() {
                let decompressed: RadixCiphertext = cpu_compressed_list
                    .get(i, &cpu_decompression_key)
                    .unwrap()
                    .unwrap();
                let decrypted: u128 = radix_cks.decrypt(&decompressed);
                assert_eq!(
                    decrypted, *message,
                    "Invalid decompression for cpu list that roundtripped Cpu->Gpu->Cpu"
                );

                let decompressed: RadixCiphertext = cpu_compressed_list_2
                    .get(i, &cpu_decompression_key)
                    .unwrap()
                    .unwrap();
                let decrypted: u128 = radix_cks.decrypt(&decompressed);
                assert_eq!(
                    decrypted, *message,
                    "Invalid decompression for cpu list that originated from Gpu"
                );
            }
        }
    }

    #[test]
    fn test_gpu_ciphertext_compression() {
        const NUM_BLOCKS: usize = 32;
        let streams = CudaStreams::new_multi_gpu();

        for (params, comp_params) in [
            (
                PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128.into(),
                COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
            ),
            (
                PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128.into(),
                COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
            ),
        ] {
            let (radix_cks, sks) =
                gen_keys_radix_gpu::<ShortintParameterSet>(params, NUM_BLOCKS, &streams);
            let cks = radix_cks.as_ref();

            let private_compression_key = cks.new_compression_private_key(comp_params);

            let (cuda_compression_key, cuda_decompression_key) = radix_cks
                .new_cuda_compression_decompression_keys(&private_compression_key, &streams);

            let max_nb_messages: usize = 2 * comp_params.lwe_per_glwe().0 / NUM_BLOCKS;

            let mut rng = rand::thread_rng();

            let message_modulus: u128 = cks.parameters().message_modulus().0 as u128;

            for _ in 0..NB_TESTS {
                // Unsigned
                let modulus = message_modulus.pow(NUM_BLOCKS as u32);
                for _ in 0..NB_OPERATOR_TESTS {
                    let nb_messages = rng.gen_range(1..=max_nb_messages as u64);
                    let messages = (0..nb_messages)
                        .map(|_| rng.gen::<u128>() % modulus)
                        .collect::<Vec<_>>();

                    let d_cts = messages
                        .iter()
                        .map(|message| {
                            let ct = radix_cks.encrypt(*message);
                            CudaUnsignedRadixCiphertext::from_radix_ciphertext(&ct, &streams)
                        })
                        .collect_vec();

                    let mut builder = CudaCompressedCiphertextListBuilder::new();

                    for d_ct in d_cts {
                        let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                        builder.push(d_and_ct, &streams);
                    }

                    let cuda_compressed = builder.build(&cuda_compression_key, &streams);

                    for (i, message) in messages.iter().enumerate() {
                        let d_decompressed: CudaUnsignedRadixCiphertext = cuda_compressed
                            .get(i, &cuda_decompression_key, &streams)
                            .unwrap()
                            .unwrap();
                        assert!(
                            d_decompressed.block_carries_are_empty(),
                            "Expected carries to be empty"
                        );
                        let decompressed = d_decompressed.to_radix_ciphertext(&streams);
                        let decrypted: u128 = radix_cks.decrypt(&decompressed);
                        assert_eq!(decrypted, *message);
                    }
                }

                // Signed
                let modulus = message_modulus.pow((NUM_BLOCKS - 1) as u32) as i128;
                for _ in 0..NB_OPERATOR_TESTS {
                    let nb_messages = rng.gen_range(1..=max_nb_messages as u64);
                    let messages = (0..nb_messages)
                        .map(|_| rng.gen::<i128>() % modulus)
                        .collect::<Vec<_>>();

                    let d_cts = messages
                        .iter()
                        .map(|message| {
                            let ct = radix_cks.encrypt_signed(*message);
                            CudaSignedRadixCiphertext::from_signed_radix_ciphertext(&ct, &streams)
                        })
                        .collect_vec();

                    let mut builder = CudaCompressedCiphertextListBuilder::new();

                    for d_ct in d_cts {
                        let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                        builder.push(d_and_ct, &streams);
                    }

                    let cuda_compressed = builder.build(&cuda_compression_key, &streams);

                    for (i, message) in messages.iter().enumerate() {
                        let d_decompressed: CudaSignedRadixCiphertext = cuda_compressed
                            .get(i, &cuda_decompression_key, &streams)
                            .unwrap()
                            .unwrap();
                        assert!(
                            d_decompressed.block_carries_are_empty(),
                            "Expected carries to be empty"
                        );
                        let decompressed = d_decompressed.to_signed_radix_ciphertext(&streams);
                        let decrypted: i128 = radix_cks.decrypt_signed(&decompressed);
                        assert_eq!(decrypted, *message);
                    }
                }

                // Boolean
                for _ in 0..NB_OPERATOR_TESTS {
                    let nb_messages = rng.gen_range(1..=max_nb_messages as u64);
                    let messages = (0..nb_messages)
                        .map(|_| rng.gen::<i64>() % 2 != 0)
                        .collect::<Vec<_>>();

                    let d_cts = messages
                        .iter()
                        .map(|message| {
                            let ct = radix_cks.encrypt_bool(*message);
                            CudaBooleanBlock::from_boolean_block(&ct, &streams)
                        })
                        .collect_vec();

                    let mut builder = CudaCompressedCiphertextListBuilder::new();

                    for d_boolean_ct in d_cts {
                        let d_ct = d_boolean_ct.0;
                        let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                        let d_and_boolean_ct =
                            CudaBooleanBlock::from_cuda_radix_ciphertext(d_and_ct.ciphertext);
                        builder.push(d_and_boolean_ct, &streams);
                    }

                    let cuda_compressed = builder.build(&cuda_compression_key, &streams);

                    for (i, message) in messages.iter().enumerate() {
                        let d_decompressed: CudaBooleanBlock = cuda_compressed
                            .get(i, &cuda_decompression_key, &streams)
                            .unwrap()
                            .unwrap();
                        assert!(
                            d_decompressed.0.holds_boolean_value(),
                            "Expected boolean block to have the degree of a boolean value"
                        );
                        let decompressed = d_decompressed.to_boolean_block(&streams);
                        let decrypted = radix_cks.decrypt_bool(&decompressed);
                        assert_eq!(decrypted, *message);
                    }
                }

                // Hybrid
                enum MessageType {
                    Unsigned(u128),
                    Signed(i128),
                    Boolean(bool),
                }
                for _ in 0..NB_OPERATOR_TESTS {
                    let mut builder = CudaCompressedCiphertextListBuilder::new();

                    let nb_messages = rng.gen_range(1..=max_nb_messages as u64);
                    let mut messages = vec![];
                    for _ in 0..nb_messages {
                        let case_selector = rng.gen_range(0..3);
                        match case_selector {
                            0 => {
                                // Unsigned
                                let modulus = message_modulus.pow(NUM_BLOCKS as u32);
                                let message = rng.gen::<u128>() % modulus;
                                let ct = radix_cks.encrypt(message);
                                let d_ct = CudaUnsignedRadixCiphertext::from_radix_ciphertext(
                                    &ct, &streams,
                                );
                                let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                                builder.push(d_and_ct, &streams);
                                messages.push(MessageType::Unsigned(message));
                            }
                            1 => {
                                // Signed
                                let modulus = message_modulus.pow((NUM_BLOCKS - 1) as u32) as i128;
                                let message = rng.gen::<i128>() % modulus;
                                let ct = radix_cks.encrypt_signed(message);
                                let d_ct = CudaSignedRadixCiphertext::from_signed_radix_ciphertext(
                                    &ct, &streams,
                                );
                                let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                                builder.push(d_and_ct, &streams);
                                messages.push(MessageType::Signed(message));
                            }
                            _ => {
                                // Boolean
                                let message = rng.gen::<i64>() % 2 != 0;
                                let ct = radix_cks.encrypt_bool(message);
                                let d_boolean_ct =
                                    CudaBooleanBlock::from_boolean_block(&ct, &streams);
                                let d_ct = d_boolean_ct.0;
                                let d_and_ct = sks.bitand(&d_ct, &d_ct, &streams);
                                let d_and_boolean_ct = CudaBooleanBlock::from_cuda_radix_ciphertext(
                                    d_and_ct.ciphertext,
                                );
                                builder.push(d_and_boolean_ct, &streams);
                                messages.push(MessageType::Boolean(message));
                            }
                        }
                    }

                    let cuda_compressed = builder.build(&cuda_compression_key, &streams);

                    for (i, val) in messages.iter().enumerate() {
                        match val {
                            MessageType::Unsigned(message) => {
                                let d_decompressed: CudaUnsignedRadixCiphertext = cuda_compressed
                                    .get(i, &cuda_decompression_key, &streams)
                                    .unwrap()
                                    .unwrap();
                                let decompressed = d_decompressed.to_radix_ciphertext(&streams);
                                let decrypted: u128 = radix_cks.decrypt(&decompressed);
                                assert_eq!(decrypted, *message);
                            }
                            MessageType::Signed(message) => {
                                let d_decompressed: CudaSignedRadixCiphertext = cuda_compressed
                                    .get(i, &cuda_decompression_key, &streams)
                                    .unwrap()
                                    .unwrap();
                                let decompressed =
                                    d_decompressed.to_signed_radix_ciphertext(&streams);
                                let decrypted: i128 = radix_cks.decrypt_signed(&decompressed);
                                assert_eq!(decrypted, *message);
                            }
                            MessageType::Boolean(message) => {
                                let d_decompressed: CudaBooleanBlock = cuda_compressed
                                    .get(i, &cuda_decompression_key, &streams)
                                    .unwrap()
                                    .unwrap();
                                let decompressed = d_decompressed.to_boolean_block(&streams);
                                let decrypted = radix_cks.decrypt_bool(&decompressed);
                                assert_eq!(decrypted, *message);
                            }
                        }
                    }
                }
            }
        }
    }

    fn test_gpu_ciphertext_re_randomization_after_compression_impl(
        radix_cks: &RadixClientKey,
        cuda_compression_key: &crate::integer::gpu::list_compression::server_keys::CudaCompressionKey,
        cuda_decompression_key: &crate::integer::gpu::list_compression::server_keys::CudaDecompressionKey,
        re_randomization_key: crate::integer::gpu::ciphertext::re_randomization::CudaReRandomizationKey<'_>,
        streams: &CudaStreams,
    ) {
        use crate::integer::ciphertext::ReRandomizationContext;

        const NUM_BLOCKS: usize = 32;
        let cks = radix_cks.as_ref();
        let rerand_domain_separator = *b"TFHE_Rrd";
        let compact_public_encryption_domain_separator = *b"TFHE_Enc";
        let metadata = b"lol".as_slice();

        let mut rng = rand::thread_rng();
        let message_modulus: u128 = cks.parameters().message_modulus().0 as u128;

        // Unsigned
        let modulus = message_modulus.pow(NUM_BLOCKS as u32);
        for _ in 0..NB_TESTS {
            let message = rng.gen::<u128>() % modulus;

            let ct = radix_cks.encrypt(message);
            let d_ct = CudaUnsignedRadixCiphertext::from_radix_ciphertext(&ct, streams);

            let mut builder = CudaCompressedCiphertextListBuilder::new();
            builder.push(d_ct, streams);
            let compressed = builder.build(cuda_compression_key, streams);

            let d_decompressed: CudaUnsignedRadixCiphertext = compressed
                .get(0, cuda_decompression_key, streams)
                .unwrap()
                .unwrap();

            // Build the seed from the CPU representation of the decompressed ciphertext
            let decompressed = d_decompressed.to_radix_ciphertext(streams);
            let mut re_randomizer_context = ReRandomizationContext::new(
                rerand_domain_separator,
                [metadata],
                compact_public_encryption_domain_separator,
            );
            re_randomizer_context.add_ciphertext(&decompressed);
            let mut seed_gen = re_randomizer_context.finalize();

            let mut d_re_randomized = d_decompressed.duplicate(streams);
            d_re_randomized
                .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap(), streams)
                .unwrap();

            let re_randomized = d_re_randomized.to_radix_ciphertext(streams);
            assert_ne!(decompressed, re_randomized);

            let decrypted: u128 = radix_cks.decrypt(&re_randomized);
            assert_eq!(decrypted, message);
        }

        // Signed
        let modulus = message_modulus.pow((NUM_BLOCKS - 1) as u32) as i128;
        for _ in 0..NB_TESTS {
            let message = rng.gen::<i128>() % modulus;

            let ct = radix_cks.encrypt_signed(message);
            let d_ct = CudaSignedRadixCiphertext::from_signed_radix_ciphertext(&ct, streams);

            let mut builder = CudaCompressedCiphertextListBuilder::new();
            builder.push(d_ct, streams);
            let compressed = builder.build(cuda_compression_key, streams);

            let d_decompressed: CudaSignedRadixCiphertext = compressed
                .get(0, cuda_decompression_key, streams)
                .unwrap()
                .unwrap();

            let decompressed = d_decompressed.to_signed_radix_ciphertext(streams);
            let mut re_randomizer_context = ReRandomizationContext::new(
                rerand_domain_separator,
                [metadata],
                compact_public_encryption_domain_separator,
            );
            re_randomizer_context.add_ciphertext(&decompressed);
            let mut seed_gen = re_randomizer_context.finalize();

            let mut d_re_randomized = d_decompressed.duplicate(streams);
            d_re_randomized
                .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap(), streams)
                .unwrap();

            let re_randomized = d_re_randomized.to_signed_radix_ciphertext(streams);
            assert_ne!(decompressed, re_randomized);

            let decrypted: i128 = radix_cks.decrypt_signed(&re_randomized);
            assert_eq!(decrypted, message);
        }

        // Boolean
        for _ in 0..NB_TESTS {
            let messages = [false, true];

            let d_cts = messages
                .iter()
                .map(|message| {
                    let ct = radix_cks.encrypt_bool(*message);
                    CudaBooleanBlock::from_boolean_block(&ct, streams)
                })
                .collect_vec();

            let mut builder = CudaCompressedCiphertextListBuilder::new();
            for d_ct in d_cts {
                builder.push(d_ct, streams);
            }
            let compressed = builder.build(cuda_compression_key, streams);

            for (i, message) in messages.iter().enumerate() {
                let d_decompressed: CudaBooleanBlock = compressed
                    .get(i, cuda_decompression_key, streams)
                    .unwrap()
                    .unwrap();

                let decompressed = d_decompressed.to_boolean_block(streams);
                let mut re_randomizer_context = ReRandomizationContext::new(
                    rerand_domain_separator,
                    [metadata],
                    compact_public_encryption_domain_separator,
                );
                re_randomizer_context.add_ciphertext(&decompressed);
                let mut seed_gen = re_randomizer_context.finalize();

                let mut d_re_randomized = d_decompressed.duplicate(streams);
                d_re_randomized
                    .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap(), streams)
                    .unwrap();

                let re_randomized = d_re_randomized.to_boolean_block(streams);
                assert_ne!(decompressed, re_randomized);

                let decrypted = radix_cks.decrypt_bool(&re_randomized);
                assert_eq!(decrypted, *message);
            }
        }
    }

    // Re-randomization with keyswitch (legacy dedicated CPK path)
    #[test]
    fn test_gpu_ciphertext_re_randomization_after_compression_with_dedicated_cpk() {
        use crate::integer::gpu::ciphertext::re_randomization::CudaReRandomizationKey;
        use crate::integer::gpu::key_switching_key::CudaKeySwitchingKeyMaterial;
        use crate::integer::key_switching_key::KeySwitchingKey;
        use crate::integer::{gen_keys_radix, CompactPrivateKey, CompactPublicKey};
        use crate::shortint::parameters::test_params::{
            TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
            TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2,
        };

        const NUM_BLOCKS: usize = 32;
        let streams = CudaStreams::new_multi_gpu();

        let params = PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        let comp_params = COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        let cpk_params = TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2;
        let rerand_ksk_params =
            TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;

        let (radix_cks, sks) = gen_keys_radix(params, NUM_BLOCKS);
        let cks = radix_cks.as_ref();

        let private_compression_key = cks.new_compression_private_key(comp_params);
        let (cuda_compression_key, cuda_decompression_key) =
            radix_cks.new_cuda_compression_decompression_keys(&private_compression_key, &streams);

        let compact_private_key = CompactPrivateKey::new(cpk_params);
        let cpk = CompactPublicKey::new(&compact_private_key);
        let ksk = KeySwitchingKey::new(
            (&compact_private_key, None),
            (&cks, &sks),
            rerand_ksk_params,
        );
        let d_ksk_material = CudaKeySwitchingKeyMaterial::from_key_switching_key(&ksk, &streams);

        let re_randomization_key = CudaReRandomizationKey::LegacyDedicatedCPK {
            cpk: &cpk,
            ksk: &d_ksk_material,
        };

        test_gpu_ciphertext_re_randomization_after_compression_impl(
            &radix_cks,
            &cuda_compression_key,
            &cuda_decompression_key,
            re_randomization_key,
            &streams,
        );
    }

    // Re-randomization without keyswitch (derived CPK path)
    #[test]
    fn test_gpu_ciphertext_re_randomization_after_compression_with_derived_cpk() {
        use crate::integer::gpu::ciphertext::re_randomization::CudaReRandomizationKey;
        use crate::integer::{gen_keys_radix, CompactPrivateKey, CompactPublicKey};

        const NUM_BLOCKS: usize = 32;
        let streams = CudaStreams::new_multi_gpu();

        let params = PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        let comp_params = COMP_PARAM_GPU_MULTI_BIT_GROUP_4_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;

        let (radix_cks, _sks) = gen_keys_radix(params, NUM_BLOCKS);
        let cks = radix_cks.as_ref();

        let private_compression_key = cks.new_compression_private_key(comp_params);
        let (cuda_compression_key, cuda_decompression_key) =
            radix_cks.new_cuda_compression_decompression_keys(&private_compression_key, &streams);

        let derived_compact_private_key: CompactPrivateKey<&[u64]> = cks.try_into().unwrap();
        let cpk = CompactPublicKey::new(&derived_compact_private_key);

        let re_randomization_key = CudaReRandomizationKey::DerivedCPKWithoutKeySwitch { cpk: &cpk };

        test_gpu_ciphertext_re_randomization_after_compression_impl(
            &radix_cks,
            &cuda_compression_key,
            &cuda_decompression_key,
            re_randomization_key,
            &streams,
        );
    }
}