# CKKS

Generated API reference for looking up CKKS classes and functions. Start with [CKKS workflow](<https://ren-docs.pages.dev/ckks/index.md>) for a runnable path, or [CKKS concepts](<https://ren-docs.pages.dev/concepts/ckks-model/index.md>) for the level, scale, and key model.

## Core objects

### `CKKSKeySet`

Bases: `PolyContainer`

CKKS parameters and device-resident key material.

#### `generate(params, *, secret_key=None, device=None, rng=None, **galois)`

Generate a complete local key set in NTT form, optionally from an existing secret key.

When `secret_key` is provided, `params.secret_key_dist` describes the distribution from which it was sampled. See :class:`GaloisKeyRequest` for the Galois key keywords.

#### `context(*, default_level=None, track_plaintext_values=False, strict_noise_bounds=False)`

Create the runtime context; `default_level` defaults to `params.default_level`.

#### `public()`

Return this key set without secret key material.

#### `get_galois_key(galois_elt)`

Return the Galois key for `galois_elt`.

#### `__reduce_ex__(_protocol)`

Realize all key material together before pickle reduces each poly.

This keeps every `Poly.__reduce__` on the already-realized fast path instead of scheduling a separate realization per key polynomial. The explicit constructor reducer also leaves runtime device placement out of the payload, so polynomials load onto the active device.

#### `polys(*others)`

Collect Poly positions in storage order, visiting shared containers once.

#### `flatten(value)`

Extract Poly fields and reusable structure, preserving shared containers.

#### `map_polys(fn)`

Transform each Poly position. The callback must not mutate the input.

#### `to(device)`

Move every polynomial to one device, preserving other stored state.

#### `replace(*, polys=None, **changes)`

Replace Poly positions and root fields with literal values.

Polys follow polys() order with an exact count; parent state is snapshotted first. Named changes use copy.replace, overriding Poly replacements through **replace**. Dataclasses run their constructor. Poly-only replacement bypasses constructors unless **tree\_reduce** rebuilds.

#### `realize()`

Realize all polynomials together.

### `CKKSContext`

Active runtime view of a CKKS key set.

Use `with ctx:` around operations that need parameter lookup, encryption, decryption, key switching, rotations, or level transitions. The key set may contain only public material for encryption/evaluation, or secret material for local tests and decryption. Entering a context selects the key set's device for new values. Access key material through `ctx.keyset`.

`default_level` is the level fresh encodings and encryptions start at; `keys.context()` defaults it to `params.default_level`. `track_plaintext_values` records diagnostic slot values during encoding, for tests and examples that compare against the exact message. Arithmetic propagates existing values regardless of this flag, and leaves them absent if an operand is untracked. `strict_noise_bounds` raises when a tracked message bound exceeds q/2; by default such bounds saturate to unbounded instead, since the tracked bounds are pessimistic enough to trip on real workloads. None of these is part of the key set or serialized.

#### `precompute_bootstrap(log_bound)`

Precompute and realize bootstrap transform plans for the given message bound.

### `Plaintext`

Bases: `SlotArithmetic[complex]`

Encoded CKKS slot vector backed by one polynomial.

Plaintexts carry the encoded polynomial plus scale/noise metadata. Most operations that read `scale` or `level` need an active `CKKSContext`.

#### `const(val, *, msg_bound=None, level=None)`

Encode a slot-constant plaintext without constructing a dense length-n coefficient vector. In coefficient space this plaintext only has nonzero terms on 1 and, for complex values with nonzero imaginary part, X^(n/2).

msg\_bound is public metadata and defaults to abs(val).

#### `encrypt(rng=None)`

Encrypt using the current context.

#### `__rmul__(other)`

```python
__rmul__(other: Plaintext | complex) -> Plaintext
```

```python
__rmul__(other: RLWECiphertext) -> RLWECiphertext
```

`other * self`: for an RLWE ciphertext, the product of both of its components with this plaintext, in the same ring and not rescaled. (A :class:`Ciphertext` has its own `*`, which rescales.)

#### `to_ciphertext()`

Returns a trivial encryption of this plaintext.

#### `rotate(steps)`

Rotate plaintext by the given number of steps.

Positive steps rotate left; negative steps rotate right. A value at slot i moves to slot (i - steps) % slot\_count.

#### `polys(*others)`

Collect Poly positions in storage order, visiting shared containers once.

#### `flatten(value)`

Extract Poly fields and reusable structure, preserving shared containers.

#### `map_polys(fn)`

Transform each Poly position. The callback must not mutate the input.

#### `to(device)`

Move every polynomial to one device, preserving other stored state.

#### `replace(*, polys=None, **changes)`

Replace Poly positions and root fields with literal values.

Polys follow polys() order with an exact count; parent state is snapshotted first. Named changes use copy.replace, overriding Poly replacements through **replace**. Dataclasses run their constructor. Poly-only replacement bypasses constructors unless **tree\_reduce** rebuilds.

#### `realize()`

Realize all polynomials together.

#### `zero(*, level=None)`

Return an encoded or trivially encrypted zero.

#### `one(*, level=None)`

Return an encoded or trivially encrypted one.

#### `to_level(level)`

Drop to the specified level, adjusting the scale accordingly.

The parameter transition owns the working rings and rounding boundaries. Its arithmetic is shared by plaintext and ciphertext conversion.

### `Ciphertext`

Bases: `SlotArithmetic[Plaintext | complex]`, `RLWECiphertext`

Encrypted CKKS value backed by two polynomial components.

Ren names the components `a` and `b`. Ciphertexts also carry scale, level, and noise metadata used by arithmetic, alignment, and diagnostics.

#### `const(val, *, msg_bound=None, level=None)`

Return a trivial encryption of a constant, with public msg\_bound defaulting to abs(val).

#### `sum(cts)`

Sum a sequence of ciphertexts, possibly at mixed levels.

See :func:`ren.schemes.ckks.arithmetic_ops.sum_ciphertexts`.

#### `multiply(cts)`

Compute the product of multiple ciphertexts.

See :func:`ren.schemes.ckks.arithmetic_ops.multiply_ciphertexts`.

#### `dot(left, right)`

Heterogeneous dot product `sum_i left[i] * right[i]`.

See :func:`ren.schemes.ckks.arithmetic_ops.dot`.

#### `bootstrap(log_bound)`

Refresh this ciphertext, assuming `abs(message) <= 2**log_bound`.

#### `rotate(step, *, max_ks=None)`

```python
rotate(step: int, *, max_ks: int | None = None) -> Ciphertext
```

```python
rotate(step: list[int], *, max_ks: int | None = None) -> list[Ciphertext]
```

Rotate ciphertext by the given number of steps, or by a list of step amounts.

Positive steps rotate left; negative steps rotate right. For each step, a value at slot i moves to slot (i - step) % slot\_count.

#### `conjugate()`

Returns a ciphertext encrypting the complex conjugate of what an input ciphertext was encrypting.

The implementation is very similar to the rotation method implementation.

#### `times_i()`

Multiplies a ciphertext by i.

#### `clone(device=None)`

Return a value-equivalent ciphertext backed by fresh polynomial storage.

#### `polys(*others)`

Collect Poly positions in storage order, visiting shared containers once.

#### `flatten(value)`

Extract Poly fields and reusable structure, preserving shared containers.

#### `map_polys(fn)`

Transform each Poly position. The callback must not mutate the input.

#### `to(device)`

Move every polynomial to one device, preserving other stored state.

#### `replace(*, polys=None, **changes)`

Replace Poly positions and root fields with literal values.

Polys follow polys() order with an exact count; parent state is snapshotted first. Named changes use copy.replace, overriding Poly replacements through **replace**. Dataclasses run their constructor. Poly-only replacement bypasses constructors unless **tree\_reduce** rebuilds.

#### `realize()`

Realize all polynomials together.

#### `zero(*, level=None)`

Return an encoded or trivially encrypted zero.

#### `one(*, level=None)`

Return an encoded or trivially encrypted one.

#### `to_level(level)`

Drop to the specified level, adjusting the scale accordingly.

The parameter transition owns the working rings and rounding boundaries. Its arithmetic is shared by plaintext and ciphertext conversion.

## Functions

### `keygen(params, *, secret_key=None, device=None, rng=None, **galois)`

Generate a complete local key set, optionally from an existing secret key.

### `encode(values, *, msg_bound, level=None)`

Encode Python values into a CKKS plaintext.

Slot i is placed at evaluation point ζ^(5^i), ensuring that the Galois automorphism σ\_5 (x -\> x^5) corresponds to slot rotation by 1.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `values` | `Sequence[complex] \| ndarray \| complex` | The values to encode. If a scalar, it is encoded as a constant polynomial, or equivalently as a polynomial with that value in every slot. | *required* |
| `msg_bound` | `float` | An upper bound on max(abs(value) for value in values), if values is a sequence, or on abs(values) if values is a scalar. | *required* |
| `level` | `int \| None` | Optional CKKS level. Defaults to the context's fresh-encryption level. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `Plaintext` | A plaintext at the selected level. |

> [!WARNING]
>
> **Public metadata**
>
> `msg_bound` is public metadata. Do not compute it from secret values.

### `decode(pt, length=None)`

Decode a CKKS plaintext back to Python complex slot values.

### `encrypt(pt, rng=None)`

Encrypt a plaintext using the active CKKS context.

The context must provide either a secret key or public key. When plaintext tracking is enabled on the context, the returned ciphertext keeps local diagnostic values for tests and examples.

### `decrypt(ct)`

Decrypt a ciphertext using the active CKKS context's secret key.

### `rerandomize(ct, rng=None)`

Rerandomize a ciphertext by adding a random ciphertext of zero.

### `bootstrap(ct_in, log_bound)`

Bootstrap a scheduled ciphertext with nominal message-magnitude bound `2**log_bound`, allowing the configured bootstrap input margin above it.

## Parameters

### `CKKSParams`

Parameters for CKKS encryption.

CKKS uses an explicit computation-level model:

- `levels[level]` gives the active moduli and nominal scale at that level
- level 0 is the lowest ordinary computation level
- `highest_level` is the highest level in the full schedule
- `bootstrap_output_level` is where bootstrapping returns ciphertexts; the levels above it are consumed by the bootstrap circuit
- `default_level` is where fresh ciphertexts start unless the context overrides it: the bootstrap output level, or `highest_level`
- `bootstrap_base_level` gives the bootstrap-input moduli q0 and scale; its moduli are a contiguous subrange of computation level 0, but its scale can differ, and it is not included in `levels`

A prefix schedule is one valid instance of this model.

Construction split:

- `from_levels(...)` is the explicit constructor for hand-authored schedules, including `u32` schedules. It takes the exact canonical key-switch digit sizes.
- `generate_prefix(...)` builds a generated prefix schedule.

#### `bootstrap_output_level`

Level at which bootstrapping returns ciphertexts, or None without bootstrapping.

#### `bootstrap_message_ratio`

How much larger q0 is than the bootstrap-input scale.

#### `default_level`

Where fresh ciphertexts start unless the context overrides it: the bootstrap output level, else the highest level.

#### `validate_security(security)`

Validate that this parameter set meets the requested security level.

#### `transition(src_level, dst_level, *, current_scale=None, correction_factor=1)`

Resolve conversion to the destination's ring and nominal scale.

Quotient-only ranges can truncate to the final working ring when it has capacity for the source scale and configured message range. Otherwise the conversion rescales directly from the source ring. Intermediate scheduled levels do not impose additional rounding boundaries.

`current_scale` overrides the source's nominal scale. The final step incorporates `correction_factor` so the represented message is approximately multiplied by that factor, rather than preserved.

#### `bootstrap_transition(*, current_scale=None, correction_factor=1)`

Resolve conversion from computation level 0 to the bootstrap base.

#### `from_levels(*, n, dtype, levels, ks_primes, log_range, ks_digit_sizes, boot_params=None, bootstrap_base_level=None, noise_dist=None, secret_key_dist=None, security=128)`

Construct params from an explicit scheduled level list.

`dtype` is a property of the whole parameter set, not of individual levels. Every derived ring in this parameter set uses that one dtype.

`ks_digit_sizes` is the exact canonical partition of the highest-level Q basis. This constructor does not infer a partitioning policy.

#### `generate_prefix(*, log_n, depth, log_precision, log_range, dtype, boot_params=None, bootstrap_level_bit_length=None, bootstrap_message_ratio=None, p_prime_count=None, p_prime_bit_length=None, ks_digit_size=None, noise_dist=None, security=128, secret_key_dist=None, log_extension_factor=0)`

Build params from a generated prefix schedule.

With `boot_params`, `bootstrap_level_bit_length` (default 60) is the target bit length of q0 and of each bootstrap level, and `bootstrap_message_ratio` (default 256) is how much larger q0 is made than the bootstrap base scale. Both are sizing policy for this generator only and are only accepted alongside `boot_params`. The resulting moduli and scale are stored in `bootstrap_base_level`.

`ks_digit_size` independently controls the maximum number of Q primes in each Method-II decomposition digit. It defaults to `p_prime_count`. `p_prime_count` defaults to the minimum generated P width for `dtype` (four primes for uint32, two for uint64).

`log_extension_factor` selects primes that are also NTT-valid for a degree-`2**log_extension_factor * n` extension ring (p ≡ 1 mod the extension ring's 2n'). KG+ transmission keys need `log_extension_factor=1` (degree 2n).

#### `python_test()`

Toy CKKS parameters for python tests (small and fast). Not secure.

#### `cuda_test()`

Toy CKKS parameters for cuda tests (medium and fast). Not secure.

#### `cheddar()`

Cheddar's fixed 40-bit modulus and level schedule with Ren bootstrapping.

Constants follow `parameters/bootparam_40.json` in `scale-snu/cheddar-fhe` at revision `8df8b26ce5411a68b68f0e7c2fb7e9a2f05f3e94`.

#### `default()`

Default CKKS parameters with 128-bit parameter security.

#### `high_precision_default()`

Default CKKS parameters for high precision.

### `CKKSLevel`

One scheduled CKKS level.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `moduli` | `Sequence[int]` | Active coefficient moduli at this level. | *required* |
| `scale` | `FloatLike` | Nominal plaintext scale at this level. | *required* |

### `CKKSTransition`

An executable conversion between CKKS representations.

Steps preserve their individual rounding boundaries. `poly_ratio` scales coefficient-domain metadata. `message_ratio` also accounts for interpreting the result at `dst_scale` and can differ slightly from one because each integer multiplier is rounded. It equals `poly_ratio * src_scale / dst_scale`. Bootstrap normalization uses this realized message ratio to restore values after converting to its separate base scale.

#### `prepare(poly)`

Apply all but the final rounding, for a shared-rescale accumulator.

### `BootstrappingParams`

CKKS bootstrapping algorithm, shared by parameter generation and execution.

The concrete bootstrap-input moduli and scale belong to :attr:`CKKSParams.bootstrap_base_level`. Prime sizing is generator policy.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `cts_depth` | `int` | Depth of the coeff-to-slots transform. | *required* |
| `stc_depth` | `int` | Depth of the slots-to-coeffs transform. | *required* |
| `exp_degree` | `int` | Degree of the exponential approximation. | *required* |
| `squaring_count` | `int` | Number of repeated squaring steps in eval-mod. | *required* |
| `failure_probability` | `float` | Target bootstrapping failure probability. | *required* |
| `precision_gains` | `Sequence[int]` | Conservative precision gain assumed before each residual correction iteration. | `()` |
| `input_margin` | `float` | Multiplicative allowance above the nominal input bound. | `1.0` |
| `sparse_encapsulation_weight` | `int \| None` | When set, key-switch to an ephemeral sparse secret of this Hamming weight only around the bootstrap mod-raise, so the mod-one interval K stays sized by the small weight rather than by the scheme secret (Bossuat-Troncoso-Pastoriza-Hubaux, https://eprint.iacr.org/2022/024). The scheme secret is then free to be dense -- keeping a dense-secret security budget, and the default when `secret_key_dist` is not given -- but may still be sparse if asked for. None (the default) disables encapsulation, which requires a sparse scheme secret to mod-raise under directly. | `None` |

#### `sparse_encapsulation`

Whether bootstrap sparse-secret encapsulation is enabled.

#### `matrix_stages(params)`

The CTS and STC factorizations, each paired with the level its first stage consumes.

#### `galois_elts_by_level(params, *, hoist)`

Galois elements this circuit uses at each level of `params`.

With `hoist` the linear transforms get a direct key per baby- and giant-step rotation, all at their input level, so they are double-hoisted; otherwise they compose base keys.
