Skip to content

Commit

Permalink
chore(doc): add compression tutorial on GPU
Browse files Browse the repository at this point in the history
  • Loading branch information
agnesLeroy committed Oct 3, 2024
1 parent 76cf276 commit 00404ca
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions tfhe/docs/guides/run_on_gpu.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,72 @@ Please refer to the [GPU benchmarks](../getting_started/benchmarks/gpu_benchmark

## Warning
When measuring GPU times on your own on Linux, set the environment variable `CUDA_MODULE_LOADING=EAGER` to avoid CUDA API overheads during the first kernel execution.

## Compressing ciphertexts after some homomorphic computation on the GPU

You can compress ciphertexts using the GPU, even after computations, just like on the [CPU](../fundamentals/compress.md#compression-ciphertexts-after-some-homomorphic-computation).

The way to do it is very similar to how it's done on the CPU.
The following example shows how to compress and decompress a list containing 4 messages:
- One 32-bits integer
- One 64-bit integer
- One Boolean
- One 2-bit integer

```rust
use tfhe::prelude::*;
use tfhe::shortint::parameters::{COMP_PARAM_MESSAGE_2_CARRY_2, PARAM_MESSAGE_2_CARRY_2};
use tfhe::{
set_server_key, CompressedCiphertextList, CompressedCiphertextListBuilder, FheBool,
FheInt64, FheUint16, FheUint2, FheUint32,
};

fn main() {
let config = tfhe::ConfigBuilder::with_custom_parameters(PARAM_MESSAGE_2_CARRY_2)
.enable_compression(COMP_PARAM_MESSAGE_2_CARRY_2)
.build();

let ck = tfhe::ClientKey::generate(config);
let compressed_server_key = tfhe::CompressedServerKey::new(&ck);
let gpu_key = compressed_server_key.decompress_to_gpu();

set_server_key(gpu_key);

let ct1 = FheUint32::encrypt(17_u32, &ck);

let ct2 = FheInt64::encrypt(-1i64, &ck);

let ct3 = FheBool::encrypt(false, &ck);

let ct4 = FheUint2::encrypt(3u8, &ck);

let compressed_list = CompressedCiphertextListBuilder::new()
.push(ct1)
.push(ct2)
.push(ct3)
.push(ct4)
.build()
.unwrap();

let serialized = bincode::serialize(&compressed_list).unwrap();

println!("Serialized size: {} bytes", serialized.len());

let compressed_list: CompressedCiphertextList = bincode::deserialize(&serialized).unwrap();

let a: FheUint32 = compressed_list.get(0).unwrap().unwrap();
let b: FheInt64 = compressed_list.get(1).unwrap().unwrap();
let c: FheBool = compressed_list.get(2).unwrap().unwrap();
let d: FheUint2 = compressed_list.get(3).unwrap().unwrap();

let a: u32 = a.decrypt(&ck);
assert_eq!(a, 17);
let b: i64 = b.decrypt(&ck);
assert_eq!(b, -1);
let c = c.decrypt(&ck);
assert!(!c);
let d: u8 = d.decrypt(&ck);
assert_eq!(d, 3);

}
```

0 comments on commit 00404ca

Please sign in to comment.