> For the complete documentation index, see [llms.txt](https://docs.zama.org/tfhe-rs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.zama.org/tfhe-rs/tfhe-rs/0.10/guides/run_on_gpu.md).

# GPU acceleration

This guide explains how to update your existing program to leverage GPU acceleration, or to start a new program using GPU.

**TFHE-rs** now supports a GPU backend with CUDA implementation, enabling integer arithmetic operations on encrypted data.

## Prerequisites

* Cuda version >= 10
* Compute Capability >= 3.0
* [gcc](https://gcc.gnu.org/) >= 8.0 - check this [page](https://gist.github.com/ax3l/9489132) for more details about nvcc/gcc compatible versions
* [cmake](https://cmake.org/) >= 3.24
* Rust version - check this [page](/tfhe-rs/tfhe-rs/0.10/guides/rust_configuration.md)

## Importing to your project

To use the **TFHE-rs** GPU backend in your project, add the following dependency in your `Cargo.toml`.

If you are using an `x86` machine:

```toml
tfhe = { version = "0.10.0", features = ["boolean", "shortint", "integer", "x86_64-unix", "gpu"] }
```

If you are using an `ARM` machine:

```toml
tfhe = { version = "0.10.0", features = ["boolean", "shortint", "integer", "aarch64-unix", "gpu"] }
```

{% hint style="success" %}
For optimal performance when using **TFHE-rs**, run your code in release mode with the `--release` flag.
{% endhint %}

### Supported platforms

**TFHE-rs** GPU backend is supported on Linux (x86, aarch64).

| OS      | x86           | aarch64          |
| ------- | ------------- | ---------------- |
| Linux   | `x86_64-unix` | `aarch64-unix`\* |
| macOS   | Unsupported   | Unsupported\*    |
| Windows | Unsupported   | Unsupported      |

## A first example

### Configuring and creating keys.

Comparing to the [CPU example](/tfhe-rs/tfhe-rs/0.10/get-started/quick_start.md), GPU set up differs in the key creation, as detailed [here](#Setting-the-keys)

Here is a full example (combining the client and server parts):

```rust
use tfhe::{ConfigBuilder, set_server_key, FheUint8, ClientKey, CompressedServerKey};
use tfhe::prelude::*;

fn main() {

    let config = ConfigBuilder::default().build();

    let client_key= ClientKey::generate(config);
    let compressed_server_key = CompressedServerKey::new(&client_key);

    let gpu_key = compressed_server_key.decompress_to_gpu();

    let clear_a = 27u8;
    let clear_b = 128u8;

    let a = FheUint8::encrypt(clear_a, &client_key);
    let b = FheUint8::encrypt(clear_b, &client_key);

    //Server-side

    set_server_key(gpu_key);
    let result = a + b;

    //Client-side
    let decrypted_result: u8 = result.decrypt(&client_key);

    let clear_result = clear_a + clear_b;

    assert_eq!(decrypted_result, clear_result);
}
```

Beware that when the GPU feature is activated, when calling: `let config = ConfigBuilder::default().build();`, the cryptographic parameters differ from the CPU ones, used when the GPU feature is not activated. Indeed, TFHE-rs uses dedicated parameters for the GPU in order to achieve better performance.

### Setting the keys

The configuration of the key is different from the CPU. More precisely, if both client and server keys are still generated by the client (which is assumed to run on a CPU), the server key has then to be decompressed by the server to be converted into the right format. To do so, the server should run this function: `decompressed_to_gpu()`.

Once decompressed, the operations between CPU and GPU are identical.

### Encryption

On the client-side, the method to encrypt the data is exactly the same than the CPU one, as shown in the following example:

```Rust
    let clear_a = 27u8;
    let clear_b = 128u8;
    
    let a = FheUint8::encrypt(clear_a, &client_key);
    let b = FheUint8::encrypt(clear_b, &client_key);
```

### Computation

The server first need to set up its keys with `set_server_key(gpu_key)`.

Then, homomorphic computations are performed using the same approach as the [CPU operations](/tfhe-rs/tfhe-rs/0.10/get-started/operations.md).

```Rust
    //Server-side
    set_server_key(gpu_key);
    let result = a + b;

    //Client-side
    let decrypted_result: u8 = result.decrypt(&client_key);

    let clear_result = clear_a + clear_b;

    assert_eq!(decrypted_result, clear_result);
```

### Decryption

Finally, the client decrypts the results using:

```Rust
    let decrypted_result: u8 = result.decrypt(&client_key);
```

## List of available operations

The GPU backend includes the following operations for both signed and unsigned encrypted integers:

| name                  | symbol         | `Enc`/`Enc`                | `Enc`/ `Int`               |
| --------------------- | -------------- | -------------------------- | -------------------------- |
| Neg                   | `-`            | :heavy\_check\_mark:       | N/A                        |
| Add                   | `+`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Sub                   | `-`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Mul                   | `*`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Div                   | `/`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Rem                   | `%`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Not                   | `!`            | :heavy\_check\_mark:       | N/A                        |
| BitAnd                | `&`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| BitOr                 | `\|`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| BitXor                | `^`            | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Shr                   | `>>`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Shl                   | `<<`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Rotate right          | `rotate_right` | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Rotate left           | `rotate_left`  | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Min                   | `min`          | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Max                   | `max`          | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Greater than          | `gt`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Greater or equal than | `ge`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Lower than            | `lt`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Lower or equal than   | `le`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Equal                 | `eq`           | :heavy\_check\_mark:       | :heavy\_check\_mark:       |
| Cast (into dest type) | `cast_into`    | :heavy\_multiplication\_x: | N/A                        |
| Cast (from src type)  | `cast_from`    | :heavy\_multiplication\_x: | N/A                        |
| Ternary operator      | `select`       | :heavy\_check\_mark:       | :heavy\_multiplication\_x: |

{% hint style="info" %}
All operations follow the same syntax than the one described in [here](/tfhe-rs/tfhe-rs/0.10/get-started/operations.md).
{% endhint %}

## Multi-GPU support

TFHE-rs supports platforms with multiple GPUs with some restrictions at the moment: the platform should have NVLink support, and only GPUs that have peer access to GPU 0 via NVLink will be used for the computation. Depending on the platform, this can restrict the number of GPUs used to perform the computation.

There is **nothing to change in the code to execute on multiple GPUs**, when they are available and have peer access to GPU 0 via NVLink. To keep the API as user-friendly as possible, the configuration is automatically set, i.e., the user has no fine-grained control over the number of GPUs to be used.

## Benchmark

Please refer to the [GPU benchmarks](/tfhe-rs/tfhe-rs/0.10/get-started/summary/gpu_benchmarks.md) for detailed performance benchmark results.

## 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](/tfhe-rs/tfhe-rs/0.10/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_KS_PBS_TUNIFORM_2M64, PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M64,
};
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_KS_PBS_TUNIFORM_2M64)
            .enable_compression(COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M64)
            .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);

}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.zama.org/tfhe-rs/tfhe-rs/0.10/guides/run_on_gpu.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
