fhelium.experimental.bootstrap
CKKS bootstrap components and full-slot bootstrap execution.
The package exposes independently replaceable polynomial, linear-transform, and modular-reduction mechanisms plus one full-slot callable configured for one Engine. Preconfigured constructors live in fhelium.experimental.bootstrap.presets.
cosine_bootstrap
function View source
def cosine_bootstrap(engine: Engine, *, profile: Literal['7/44', '8/28', '8/28-s2c3', '3/30']='7/44', message_domain: Literal['complex', 'real']='complex', polynomial_evaluator: Any | None=None, giant_step_reduction: Literal['aggregate', 'independent'] | None=None, coeffs_to_slots_evaluator: Any | None=None, slots_to_coeffs_evaluator: Any | None=None, product_implementation: str | None='auto', product_chunk_size: int | None=16, retain_diagonals: bool=True, compress_diagonals: bool=True, retain_constants: bool=True, batch_modular_branches: bool=True, modulus_raising: ModulusRaising | None=None, source_depth: int | None=None, input_depth: int | None=None, input_scale: float | None=None, target_scales: Sequence[float] | None=None, modup_method: Literal['exact', 'crt', 'normalized_crt']='exact') -> FullSlotBootstrap: ...Construct a full-slot cosine Bootstrap with inspectable choices.
"7/44" uses seven double-angle iterations, a degree-44 Chebyshev seed, Blocked evaluation with baby step eight, and aggregate giant-step quotients. "8/28" uses eight iterations and a degree-28 seed; "8/28-s2c3" adds a third SlotsToCoeffs stage. Both degree-28 profiles default to Binary evaluation and independent giant quotients. These three profiles have raw branch bound
"3/30" selects raw bound B=32, four CoeffsToSlots stages, an even degree-30 seed evaluated through T2 and a degree-15 Blocked schedule, three double-angle iterations and three SlotsToCoeffs stages. The seed coordinate shifts by -1/64. Transform scaling and slot normalization occur in the last forward stage; the following coefficient product aligns scale. Its input range must be established for the chosen modulus-raising relation.
modulus_raising binds the selected raising component. source_depth, input_depth and input_scale define entry coordinates, while target_scales supplies coefficient-product targets for each depth. The example encapsulation parameters specify these values together.
Defaults are based on the logN16, generator-five, approximately remaining_depth and refresh_window and validate the decoded error for the intended parameter and message range.
polynomial_evaluator replaces the profile's polynomial schedule. giant_step_reduction selects QP accumulation followed by one quotient, or independent per-giant rescale and key switching. These schedules differ in rounding and workspace. A supplied linear evaluator is used unchanged; product and giant-step shortcuts configure only the default evaluators. Construct FullSlotBootstrap directly for custom transform compilers or modular-reduction components.
product_implementation="auto" selects weighted-product implementations from represented data and device. None selects native products, and a registered name requests that implementation. product_chunk_size=16 bounds fused product terms. Retaining diagonals and constants trades resident memory for repeated preparation; compress_diagonals losslessly compresses eligible encoded data. Branch batching applies to complex messages. Real messages require generator-five radix-2 reconstruction.
CenteredModRaise
class View source
CenteredModRaise()Extend each component's centered CRT representative into target Q.
The lifted decryption phase contains the source modulus times an integer polynomial. The following Fourier and periodic reduction handle that term.
EncapsulatedModRaise
class View source
EncapsulatedModRaise(low_key: KeySwitchKey, return_key: KeySwitchKey, low_p_moduli: tuple[int, ...], return_prime: int, return_p_moduli: tuple[int, ...], moddown_rounding: Literal['nearest', 'floor'] = 'nearest')Bind low and return hints for an intermediate secret relation.
low_key encrypts P_lowE_js under t. return_key has one digit encrypting guardP_returnt under s. Both are ordinary KeySwitchKey values; the component retains their live tensors, not either secret. Execution switches to t, centered-raises, then returns to s before Fourier transforms. Secret distributions, modulus choices and reducer range are caller choices.
Attributes
| Name | Type | Default/value |
|---|---|---|
low_key | KeySwitchKey | |
return_key | KeySwitchKey | |
low_p_moduli | tuple[int, ...] | |
return_prime | int | |
return_p_moduli | tuple[int, ...] | |
moddown_rounding | Literal['nearest', 'floor'] | 'nearest' |
ScaledModRaise
class View source
ScaledModRaise(inner: ModulusRaising, multiplier: int)Raise the modulus and multiply its internal scale by an integer.
For the wrapped result (c, Delta), integer payload multiplication followed by the corresponding scale transition produces (kc, kDelta), preserving its represented message. The following transform schedule consumes its existing Q groups; this component adds no modulus rows and performs no rescale. Existing decoded error is unchanged; the larger scale reduces the normalized contribution of subsequent key-switch errors. The multiplier is a mathematical scale choice shared by Eager and captured execution.
Attributes
| Name | Type | Default/value |
|---|---|---|
inner | ModulusRaising | |
multiplier | int |
ModulusRaising
class View source
ModulusRaising()Bases: Protocol
Map source Q coordinates to coefficient/standard target Q ciphertexts.
EvenChebyshevEvaluator
class View source
EvenChebyshevEvaluator(evaluator: Any)Evaluate sum a_(2j) T_(2j)(x) as sum a_(2j) T_j(T2(x)).
evaluator selects the inner polynomial schedule. Forming T2(x)=2x²−1 consumes one ciphertext multiplication, relinearization and complete Q group rescale. The inner evaluator consumes the resulting actual scale. Odd coefficients must be zero; constants use the inner evaluator directly. Output preserves input representation and batch axes.
Attributes
| Name | Type | Default/value |
|---|---|---|
evaluator | Any |
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...] | None: ...Compose the actual T2 product and the folded evaluator's consumers.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...BlockedChebyshevEvaluator
class View source
BlockedChebyshevEvaluator(baby_step: int | None = None, skip_near_zero: float = 0.0)Evaluate
Descending elimination uses baby_step=None,
At final depth
Input and output are CT2 over Q with the same batch axes. The input domain is preserved when retaining NTT; otherwise output is coefficient form. NTT intermediates follow BootstrapArithmetic.retain_ntt. The approximation's domain remains caller-owned; complex inputs are evaluated as
Attributes
| Name | Type | Default/value |
|---|---|---|
baby_step | int | None | None |
skip_near_zero | float | 0.0 |
plan
method
def plan(polynomial: PolynomialApproximation) -> ChebyshevBlockPlan: ...Return the shared coefficient, basis, depth and operation plan.
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...Return the depth consumed by this polynomial's selected plan.
operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...Count products, relinearizations and group rescales in the plan.
relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...]: ...Return basis-product depths and the single delayed giant-sum depth.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...Execute the plan, retaining actual scales and the input domain.
ChebyshevBlockPlan
class View source
ChebyshevBlockPlan(polynomial: PolynomialApproximation, baby_step: int, coefficients: tuple[tuple[complex, ...], ...], basis_depths: tuple[tuple[int, int], ...], required_depths: int, inventory: tuple[tuple[str, int], ...])Coefficient blocks, shared binary nodes and their depth schedule.
coefficients[j][i] multiplies T_i(x) T_(j*m)(x). A baby step of zero denotes the direct low-degree schedule. basis_depths records each node's depth relative to the input, in dependency order.
Attributes
| Name | Type | Default/value |
|---|---|---|
polynomial | PolynomialApproximation | |
baby_step | int | |
coefficients | tuple[tuple[complex, ...], ...] | |
basis_depths | tuple[tuple[int, int], ...] | |
required_depths | int | |
inventory | tuple[tuple[str, int], ...] |
BalancedPowerEvaluator
class View source
BalancedPowerEvaluator(skip_near_zero: float = 0.0)Evaluate a power series through a shared balanced product tree.
To construct
evaluate consumes a two-component coefficient-domain, standard-RNS Q ciphertext representing the basis coordinate [component, *batch, limb, coefficient]; all batch members share depth, scale, and prime_ids. The method is functional. Each ciphertext product converts operands to NTT/Montgomery form, multiplies to three components, relinearizes back to two coefficient-domain standard components, and rescales by the complete Q group product while retaining actual scale. The final result is coefficient-domain standard RNS over Q at ciphertext.depth + required_depths(polynomial), with the corresponding prime_ids, unchanged batch shape, two components, and the coefficient-product target scale.
Attributes
| Name | Type | Default/value |
|---|---|---|
skip_near_zero | float | 0.0 |
operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...Return multiplying operations in the shared power schedule.
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...Count the deepest shared power node plus its coefficient rescale.
relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...]: ...Return product-input depths of the required shared power nodes.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...Evaluate
Coefficients with magnitude at or below skip_near_zero are omitted. A constant-only polynomial still consumes one depth by multiplying the input by zero; this keeps the execution behavior equal to the declared one-depth cost. Inputs are not mutated and output storage does not alias an input.
BootstrapArithmetic
class View source
BootstrapArithmetic(engine: Engine, constant_cache: MutableMapping[object, object] | None = None, retain_ntt: bool = True, modup_method: Literal['exact', 'crt', 'normalized_crt'] = 'exact')Execute Bootstrap CKKS arithmetic with depth-dependent scale targets.
target_scales gives an inspectable multiplication schedule derived from Q group products. Scalar and diagonal products select their plaintext scales to reach that schedule; ciphertext products retain actual scales. constant_cache retains compact scalar plaintexts and monomial tables for reuse across evaluation calls. Scalar entries preserve the first stochastic encoding sample; a hit does not advance rounding state. Clearing or omitting the cache permits fresh encoding. Scalar preparation requires max(abs(real(c)), abs(imag(c))) * scale < 2**63 before conversion to signed-integer polynomial coefficients. Addition uses the ciphertext scale; multiplication uses its selected plaintext scale. Values outside this preparation bound raise ValueError. retain_ntt=False selects coefficient-domain results for callers that compose Bootstrap without NTT-retaining Eager operations. FullSlotBootstrap creates this owner internally; custom compositions pass it to linear, polynomial, and periodic-reduction evaluators.
Attributes
| Name | Type | Default/value |
|---|---|---|
engine | Engine | |
constant_cache | MutableMapping[object, object] | None | None |
retain_ntt | bool | True |
modup_method | Literal['exact', 'crt', 'normalized_crt'] | 'exact' |
target_scales
property
target_scales: tuple[float, ...]Return the selected per-depth arithmetic scales.
The default selection is computed backward from the terminal default scale using for_input follows an actual input scale forward over the requested depths. scaled_targets instead describes coefficient accumulators multiplied by unscaled basis nodes.
for_input
method
def for_input(ciphertext: Ciphertext, required_depths: int) -> BootstrapArithmetic: ...Follow
Polynomial basis nodes use this recurrence through their required depths; coefficient products may select a different output scale.
scaled_targets
method
def scaled_targets(factor: float) -> BootstrapArithmetic: ...Use a common scale factor for polynomial coefficient accumulators.
plaintext_scale
method
def plaintext_scale(input_scale: float, depth: int) -> float: ...Choose
multiply_by_monomial
method
def multiply_by_monomial(ciphertext: Ciphertext, exponent: int) -> Ciphertext: ...Return
align_depths
method
def align_depths(lhs: Ciphertext, rhs: Ciphertext) -> tuple[Ciphertext, Ciphertext]: ...Advance the shallower value to the deeper value's Q depth.
advance_depth
method
def advance_depth(ciphertext: Ciphertext) -> Ciphertext: ...Advance one Q group and return at the next target scale.
relinearize
method
def relinearize(ciphertext: Ciphertext, key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey], *, output_domain: Literal['coefficient', 'ntt']='coefficient', rescale: bool=False) -> Ciphertext: ...Reduce
A primitive key is consumed directly. During material preparation an inventory selects a key covering the product's Q rows. Prepared execution reads its selected per-depth references. The lift method and requested polynomial representation are forwarded to the Eager operation. Without rescaling, Q depth and actual scale are preserved. With rescale=True, the operation removes the next complete Q group
multiply_relinearize_rescale
method
def multiply_relinearize_rescale(lhs: Ciphertext, rhs: Ciphertext, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey]) -> Ciphertext: ...Return relinearized
multiply_scalar
method
def multiply_scalar(ciphertext: Ciphertext, scalar: complex) -> Ciphertext: ...Multiply by one encoded scalar, rescale, and return target scale.
weighted_scalar_sum
method
def weighted_scalar_sum(terms: Sequence[tuple[Ciphertext, complex]]) -> Ciphertext: ...Return
add_scalar
method
def add_scalar(ciphertext: Ciphertext, scalar: complex) -> Ciphertext: ...Add a scalar without changing depth, scale, domain, or RNS basis.
BinaryDecompositionChebyshevEvaluator
class View source
BinaryDecompositionChebyshevEvaluator(skip_near_zero: float = 0.0)Evaluate a Chebyshev series through shared doubling identities.
The evaluator builds only basis elements required by nonzero terms. It recursively uses
Shared basis nodes are retained until their last polynomial or recurrence consumer. Depth-specific
The coordinate, tensor axes, arithmetic-state preconditions, functional behavior, per-product transitions, output depth, active prime_ids, and depth-dependent scale schedule match BalancedPowerEvaluator; only the polynomial basis and multiplication DAG differ.
Attributes
| Name | Type | Default/value |
|---|---|---|
skip_near_zero | float | 0.0 |
operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...Return multiplying operations in the shared basis schedule.
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...Count the deepest shared basis node plus its coefficient rescale.
relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...]: ...Return product-input depths of the required shared basis nodes.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...Build required
Terms at or below skip_near_zero are omitted. A constant-only polynomial consumes one depth, as reported by required_depths. The method is functional and returns a two-component coefficient-domain standard-RNS Q value at the arithmetic owner's target scale.
ChebyshevInterpolator
class View source
ChebyshevInterpolator(degree: int, error_samples: int = 8193)Fit a degree-limited Chebyshev series at first-kind nodes.
degree controls both the number of interpolation nodes and the highest returned term error_samples controls only the dense grid used to report max_error; that sampled value is not a proof of the uniform error between grid points.
Attributes
| Name | Type | Default/value |
|---|---|---|
degree | int | |
error_samples | int | 8193 |
approximate
method
def approximate(function: Callable[[np.ndarray], np.ndarray], *, domain: tuple[float, float]=(-1.0, 1.0), name: str='polynomial') -> PolynomialApproximation: ...Interpolate after mapping physical
If domain=(a, b), first-kind nodes
Coefficients in the returned object are functions of normalized
max_error is measured on error_samples equally spaced normalized coordinates after fitting. Approximation runs on CPU binary64/complex128 arrays and returns no encrypted tensor.
CosineDoubleAngleReduction
class View source
CosineDoubleAngleReduction(input_bound: int, double_angle_iterations: int, approximator: Any, evaluator: Any, fuse_input_normalization: bool = False, retain_ntt: bool = False, maximum_plaintext_error: float = 0.001, seed_shift: float = 0.0)Reduce one real branch with a cosine seed and double-angle chain.
input_bound is the positive integer seed_shift places its seed polynomial at a shifted coordinate. With double_angle_iterations, the unshifted seed is
and iteration
Thus seed_shift=c evaluates the seed at z=x+c and subtracts the same shift in its fitted phase. The periodic map is unchanged. For c=-1/(2B), the fitted seed is even; its odd Chebyshev coefficients are zero. Approximation and homomorphic evaluation are separate components.
reference(values) always takes normalized evaluate(...) takes raw fuse_input_normalization=False, dividing by
The homomorphic input is a two-component Q ciphertext in either coefficient/standard or NTT/Montgomery representation, with payload axes [component, *batch, limb, coefficient], active prime_ids, and actual scale matching the arithmetic owner's target at the input depth. Evaluation is functional. With retain_ntt=True, a coefficient input is transformed once and the polynomial and double-angle chain retain NTT/Montgomery form until one final inverse transform. Otherwise each multiplication returns to the input representation. Rescale removes one Q group and divides actual scale by its product. The output uses the input representation, batch and component axes, Q basis, and context; its depth advances by required_depths, its limb axis contains the corresponding suffix of prime_ids, and its actual scale follows the arithmetic owner's depth schedule.
More iterations reduce the seed frequency but each iteration costs one ciphertext multiplication, relinearization, and rescale depth. Neither the class nor evaluate measures the encrypted branch range; the caller must establish
Attributes
| Name | Type | Default/value |
|---|---|---|
requires_relinearization | True | |
input_bound | int | |
double_angle_iterations | int | |
approximator | Any | |
evaluator | Any | |
fuse_input_normalization | bool | False |
retain_ntt | bool | False |
maximum_plaintext_error | float | 0.001 |
seed_shift | float | 0.0 |
polynomial
property
polynomial: PolynomialApproximationFit the low-frequency seed in normalized coordinate
For double_angle_iterations, the returned Chebyshev or power series in z=x+seed_shift approximates
Its coefficient basis is selected by approximator; coefficients use that basis's ascending-degree convention.
approximation_error
property
approximation_error: floatSample
The grid spans normalized
fused_input_divisor
property
fused_input_divisor: floatReturn
required_depths
property
required_depths: intCount normalization, polynomial-evaluation, and recurrence depths.
relinearization_depths
method
def relinearization_depths(*, input_depth: int=0) -> tuple[int, ...] | None: ...Compose normalization, polynomial products and double-angle products.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None, conjugation_key: ConjugationKey | None=None) -> Ciphertext: ...Evaluate
With non-fused normalization the input represents raw ciphertext.depth + required_depths. Input storage is not mutated or aliased by the result.
reference
method
def reference(values: np.ndarray) -> np.ndarray: ...Evaluate the plaintext oracle on normalized coordinates
values may have any NumPy-broadcastable shape and that shape is preserved. Unlike non-fused evaluate, this method never divides by values / input_bound. The target is
DiagonalBSGSEvaluator
class View source
DiagonalBSGSEvaluator(baby_step: int, hoist_baby_rotations: bool = True, rotation_schedule: Literal['auto', 'group_major', 'baby_major'] = 'auto', baby_steps_by_transform: Mapping[str, int] | None = None, group_batch_size: int = 16, product_implementation: str | None = None, product_chunk_size: int | None = None, giant_step_reduction: Literal['aggregate', 'independent'] = 'aggregate', modup_method: Literal['exact', 'crt', 'normalized_crt'] | None = None)Execute a diagonal map with shared BSGS rotations and live-set scheduling.
Splitting an offset as
rotation_schedule="group_major" retains shared baby rotations and finishes at most group_batch_size giant groups at a time. Each baby is released after its last group consumer. "baby_major" generates one baby at a time and updates the giant-group accumulators. "auto" selects baby-major when there are fewer giant groups than distinct babies, otherwise group-major. The selected traversal is available through schedule_for. Group batches share ciphertext loads in one represented weighted sum; the default batch size is sixteen, and one selects immediate single-group completion.
product_implementation and product_chunk_size select the weighted product consumer. None retains native selection. Group-major traversal exposes multi-term rows; baby-major traversal honors the same request with one-term calls and preserves its live set. "auto" resolves by operand representation, device and registered Backend capabilities.
giant_step_reduction="aggregate" streams giant key products into one QP accumulator, then divides once by "independent" rescales and key-switches each giant separately before summing its Q result. These schedules differ in rounding and temporary storage. At depth
Direct baby keys share one hybrid decomposition when hoist_baby_rotations is true. Composed inventories use the supplied rotation callable. baby_steps_by_transform selects named-stage steps.
Attributes
| Name | Type | Default/value |
|---|---|---|
baby_step | int | |
hoist_baby_rotations | bool | True |
rotation_schedule | Literal['auto', 'group_major', 'baby_major'] | 'auto' |
baby_steps_by_transform | Mapping[str, int] | None | None |
group_batch_size | int | 16 |
product_implementation | str | None | None |
product_chunk_size | int | None | None |
giant_step_reduction | Literal['aggregate', 'independent'] | 'aggregate' |
modup_method | Literal['exact', 'crt', 'normalized_crt'] | None | None |
required_depths
method
def required_depths(transform: Any) -> int: ...Return the single rescale consumed by one BSGS stage.
baby_step_for
method
def baby_step_for(transform: DiagonalLinearTransform) -> int: ...Return the caller-selected BSGS step for one compiled transform.
schedule_for
method
def schedule_for(transform: DiagonalLinearTransform) -> str: ...Select a traversal from the stage's represented baby/group counts.
required_rotation_offsets
method
def required_rotation_offsets(transform: Any) -> tuple[int, ...]: ...Return the union of nonzero baby and giant rotations.
baby_rotation_offsets
method
def baby_rotation_offsets(transform: DiagonalLinearTransform) -> tuple[int, ...]: ...Return BSGS baby steps independently of decomposition sharing.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, transform: Any, *, rotation_paths: Mapping[int, tuple[RotationKey, ...]], rotate: Callable[[Ciphertext, int], Ciphertext], encode_diagonal: Callable[..., Plaintext | CompressedPlaintext]) -> Ciphertext: ...Evaluate
Group-major uses the ordinary represented plaintext-product sum for a bounded block of groups. Baby-major accumulates terms in the same baby order. Giant groups finish in increasing offset order using the selected shared or independent quotient schedule. Composed rotation inventories retain prefix key switches; the aggregate schedule combines their final switches. The shared quotient divides by the complete Q depth group. Diagonal material preparation and retention remain caller-owned.
DiagonalLinearTransform
class View source
DiagonalLinearTransform(diagonals: Mapping[int, ArrayLike], slots: int, name: str = 'diagonal_linear_transform')An immutable cyclic-diagonal linear map over packed CKKS slots.
The map is
Each stored diagonal is a CPU complex128 NumPy vector with shape [slot]; reference accepts and returns the same one-dimensional shape. An evaluator chooses the execution algorithm for these diagonals. Offsets are cyclic modulo -1 and slots - 1 are combined by normalized_diagonals.
Attributes
| Name | Type | Default/value |
|---|---|---|
diagonals | Mapping[int, ArrayLike] | |
slots | int | |
name | str | 'diagonal_linear_transform' |
normalized_diagonals
method
def normalized_diagonals() -> dict[int, np.ndarray]: ...Map every offset to
The stored arrays remain immutable. A new mapping is returned because two input offsets can normalize to the same cyclic key and must then be added elementwise. Returned vectors retain shape [slot].
reference
method
def reference(values: ArrayLike) -> np.ndarray: ...Apply
values must have shape [slot]. The returned CPU complex128 array has shape [slot]. This plaintext oracle does not encode, rescale, consume depths, or model CKKS error.
DirectDiagonalEvaluator
class View source
DirectDiagonalEvaluator()Evaluate each cyclic diagonal independently, then rescale once.
For every nonzero offset this strategy rotates the input, multiplies it by the corresponding encoded diagonal, and adds the product to an accumulator. All products have pending scale
The input is a two-component coefficient-domain standard-RNS Q ciphertext with data axes [component, *batch, limb, coefficient], ring extent prime_ids tuple. If the removed Q group has product
and Q prime_ids with the complete group removed. The output remains in coefficient domain with standard residues; temporary diagonal plaintexts are NTT-domain Montgomery RNS. The result does not alias an input.
required_depths
method
def required_depths(transform: Any) -> int: ...Return the single rescale consumed by one diagonal stage.
required_rotation_offsets
method
def required_rotation_offsets(transform: Any) -> tuple[int, ...]: ...Return direct non-zero diagonal offsets.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, transform: Any, *, rotation_paths: Mapping[int, tuple[RotationKey, ...]], rotate: Callable[[Ciphertext, int], Ciphertext], encode_diagonal: Callable[..., Plaintext | CompressedPlaintext]) -> Ciphertext: ...Apply
The input must match the engine's slot count. For offset zero the input is reused directly; every other term requests one rotation through the supplied rotation-key strategy. Each diagonal is encoded at the input depth, multiplied into its rotated ciphertext, and accumulated at pending scale. A single final rescale advances the output by one depth.
Raises
TypeError: Iftransformuses another stage representation.ValueError: If slot count or diagonal content is invalid.
FullSlotBootstrap
class View source
FullSlotBootstrap(engine: Engine, *, coeffs_to_slots_compiler: Any, coeffs_to_slots_evaluator: Any, modular_reduction: Any, slots_to_coeffs_compiler: Any, slots_to_coeffs_evaluator: Any, modulus_raise_target_depth: int=0, modulus_raising: ModulusRaising | None=None, source_depth: int | None=None, input_depth: int | None=None, input_scale: float | None=None, target_scales: Sequence[float] | None=None, modup_method: Literal['exact', 'crt', 'normalized_crt']='exact', normalization_stage: int | None=None, retain_diagonals: bool=False, compress_diagonals: bool=True, message_domain: Literal['complex', 'real']='complex', retain_constants: bool=False, batch_modular_branches: bool=False)Full-slot refresh callable with prepared transforms and replaceable components.
Construction configures transform compilers/evaluators and modular reduction for one engine. Calling the object executes the visible full-slot algorithm with primitive key references selected from an application-owned inventory.
compress_diagonals=True selects the minimum lossless contiguous storage of each encoded NTT diagonal. retain_diagonals keeps these materials between calls. retain_constants similarly keeps the scalar, entry, and monomial constants used by the circuit between calls. If batch_modular_branches is true, the real and imaginary periodic reductions share one dense branch-batch execution before being unpacked.
source_depth selects the Q suffix consumed by modulus raising. input_depth may equal it or its preceding group; the latter entry multiplies by an integer and rescales into the source basis. Defaults use the terminal basis and its preceding group. modulus_raising selects centered extension or an intermediate-secret construction.
Let input_scale, input_bound and let fused_input_divisor, equal to
If
The encrypted transform followed by multiplication by
the idealized nonlinear and inverse-transform portion is
message_domain="complex" uses this two-branch map. For real-valued slot messages, message_domain="real" requires the generator-5 radix-2 STC compiler and evaluates only
Polynomial approximation, CKKS arithmetic, and key switching perturb this idealized map. The caller must establish the reducer's raw-coordinate precondition
remaining_depth
property
remaining_depth: intReturn Q depth transitions available after this Bootstrap.
refresh_window
property
refresh_window: intReturn transitions from the refreshed output to the next entry depth.
required_rotations
property
required_rotations: tuple[int, ...]Return normalized signed
key_steps
method
def key_steps(rotation_key_strategy: str='all_required') -> tuple[int, ...]: ...Return the standalone rotation basis requested by a generation strategy.
signed_power_of_two stores the signed-power components needed to compose the transform rotations. signed_power_of_two_with_baby_steps adds direct keys for every BSGS baby step. all_required stores a direct key for every required transform rotation.
An existing inventory can satisfy signed-power requests with more direct paths. all_required still requires direct transform keys; signed_power_of_two_with_baby_steps requires direct baby keys. Baby decomposition sharing additionally requires compatible stored layouts and the evaluator's hoist_baby_rotations choice.
Parameters
rotation_key_strategy: Rotation-key inventory to enumerate.
Raises
ValueError: If the rotation-key strategy is not supported.
evaluation_key_requirements
method
def evaluation_key_requirements(rotation_key_strategy: str='all_required') -> EvaluationKeyRequirements: ...Return the capability description of the standalone rotation basis.
Rotation steps come from key_steps. Conjugation is always required by full-slot reconstruction; relinearization is required only when the selected modular reduction declares ciphertext products. The result contains no key tensors. Reuse from a shared inventory can replace composed paths with available direct keys.
create_evaluation_keys
method
def create_evaluation_keys(secret_key: SecretKey, *, into: EvaluationKeySet | None=None, rotation_key_strategy: str='all_required', device: torch.device | str | None=None) -> EvaluationKeySet: ...Populate a shared inventory with evaluation keys for this composition.
The default all_required strategy provisions direct transform keys. Existing paths satisfying the selected direct-key requirements are reused by reference. Missing rotations are generated from a consumer-wide layout choice accounting for shared steps and additional key storage. Relinearization and conjugation capabilities are provisioned through the engine's primitive factories. The returned inventory is into when supplied; other members remain available to their consumers. The caller supplies keys for one secret relation and mathematical parameter context.
cached_diagonal_bytes
property
cached_diagonal_bytes: intReturn encoded diagonal bytes retained by ordinary evaluations.
cached_constant_bytes
property
cached_constant_bytes: intReturn scalar and monomial bytes retained by ordinary evaluations.
clear_cache
method
def clear_cache() -> None: ...Release this callable's ordinary caches.
PreparedBootstrapCore objects own separate dictionaries and retain their materials independently. Close Graphs using ordinary evaluations first.
entry
method
def entry(ciphertext: Ciphertext) -> tuple[Ciphertext, float]: ...Return source-basis coordinates and their output scale compensation.
For entry group product M, integer k=max(1, ceil(MDelta0/Delta_in)) gives Delta_b=kDelta_in/M after nearest rescale. Direct source-basis entry instead uses Delta_b=Delta_in without this transition. The returned payload is interpreted at Delta0; tau=Delta_b/Delta0 restores the original message coordinate in finish. The input is preserved.
core
method
def core(coordinate: Ciphertext, *, evaluation_keys: EvaluationKeySet) -> Ciphertext: ...Evaluate the normalized core with the ordinary retention controls.
coordinate is the source-basis result of entry. Use prepare_core to bind retained materials before repeated execution or CUDA capture.
finish
method
def finish(core_result: Ciphertext, entry_scale_ratio: float) -> Ciphertext: ...Return a fresh envelope with scale Delta_out * entry_scale_ratio.
Payload storage is shared with core_result. Its original metadata remains unchanged, including when it is a borrowed Graph output.
prepare
method
def prepare(example_input: Ciphertext, *, evaluation_keys: EvaluationKeySet) -> PreparedBootstrap: ...Bind a complete refresh for Eager execution or callable Compile.
Preparation follows the existing core material discovery once. Newly encoded materials consume the encoding RNG; later calls and Compile capture only read those materials. The prototype payload is not retained.
prepare_core
method
def prepare_core(coordinate: Ciphertext, *, evaluation_keys: EvaluationKeySet) -> PreparedBootstrapCore: ...Bind and prepare a core for the post-entry input's state and device.
Preparation executes the core once to discover and retain its diagonal, scalar and structural materials. It performs real arithmetic and advances the encoding RNG for new materials. The temporary output and prototype payload are released; only the signature, selected component objects, key values and prepared materials are retained. Call before CUDA capture.
PreparedBootstrapCore
class View source
PreparedBootstrapCore(algorithm: _CoreAlgorithm, materials: _CoreMaterials, input_signature: ValueSignature, device: torch.device)Callable owning one core's component bindings, keys and prepared materials.
FullSlotBootstrap.prepare_core constructs this object for a post-entry coordinate. Its signature and device fix value state, shape, dtype and layout without retaining the prototype payload. Storage strides may differ: encoded materials are shared by strided inputs and packed Graph buffers. Component objects and evaluation-key values are selected during preparation and retained in ordinary lookup mappings. Appending or removing keys in the caller's inventory leaves these selections unchanged. Configure components before preparation and prepare again after changing them. Different prepared cores have independent material dictionaries.
A captured Graph retains its callable and therefore these materials. Close every Graph using this object before calling close. Closing releases the material and key references and ends host-call use.
evaluation_keys
property
evaluation_keys: EvaluationKeySetReturn a reference inventory of this core's selected evaluation keys.
cached_diagonal_bytes
property
cached_diagonal_bytes: intReturn logical bytes in the owned encoded diagonal materials.
cached_constant_bytes
property
cached_constant_bytes: intReturn logical bytes in the owned scalar and monomial materials.
close
method
def close() -> None: ...Release bindings after all Graphs using this core have been closed.
PreparedBootstrap
class View source
PreparedBootstrap(core: PreparedBootstrapCore, input_signature: ValueSignature)Complete entry/core/finish refresh with prepared public materials and keys.
The instance is an ordinary callable for Eager or Compile. Its core owns the encoded materials; neither the preparation input nor an output is retained. Close captured Graphs before closing this owner. Existing linked executables retain their own bound Tensor references.
evaluation_keys
property
evaluation_keys: EvaluationKeySetReturn this prepared execution's selected primitive key references.
cached_diagonal_bytes
property
cached_diagonal_bytes: intcached_constant_bytes
property
cached_constant_bytes: intclose
method
def close() -> None: ...Release the prepared owner after its captured Graphs are closed.
HornerPowerEvaluator
class View source
HornerPowerEvaluator()Evaluate a power polynomial by a corrected depth-aware Horner chain.
For degree
and then applies
A constant polynomial consumes one depth by multiplying the input by zero. A linear polynomial consumes one coefficient-multiplication depth and requires no relinearization key. Degree
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...Return one depth for constants or the declared power degree.
relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...]: ...Return Horner product depths after the leading coefficient rescale.
operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...Return the corrected-Horner multiplication inventory.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...Evaluate a power polynomial with a corrected Horner recurrence.
The input must be a complete two-component coefficient-domain, standard-RNS Q ciphertext at its recorded actual scale. The method validates all context, key, scale, and available-depth requirements before allocating encrypted temporaries. The functional output is in the same arithmetic state at ciphertext.depth + required_depths(polynomial) and the arithmetic owner's target scale.
PatersonStockmeyerPowerEvaluator
class View source
PatersonStockmeyerPowerEvaluator(baby_step: int)Evaluate a power polynomial with one fixed baby-step size.
baby_step=k is part of the evaluator identity and is never selected at runtime. The evaluator writes
Balanced shared powers
Basis powers follow the input's actual scale recurrence. Coefficient accumulators use a common multiple of those scales chosen so the final product reaches the requested output scale. This keeps additions coherent without changing the polynomial's coefficients or its input coordinate.
The declared coefficient tuple, including zero entries, fixes the schedule. baby_step determines the product DAG and its required depths.
Attributes
| Name | Type | Default/value |
|---|---|---|
baby_step | int |
required_depths
method
def required_depths(polynomial: PolynomialApproximation) -> int: ...Return the critical-path depth cost for this fixed k.
operation_inventory
method
def operation_inventory(polynomial: PolynomialApproximation) -> dict[str, int]: ...Return ciphertext, coefficient, and alignment counts.
relinearization_depths
method
def relinearization_depths(polynomial: PolynomialApproximation, *, input_depth: int=0) -> tuple[int, ...]: ...Return basis and aligned giant-product depths from the fixed schedule.
evaluate
method
def evaluate(arithmetic: BootstrapArithmetic, ciphertext: Ciphertext, polynomial: PolynomialApproximation, *, relinearization_key: RelinearizationKey | EvaluationKeySet | Mapping[int, RelinearizationKey] | None=None) -> Ciphertext: ...Evaluate with the fixed baby/giant schedule and depth caches.
PolynomialApproximation
class View source
PolynomialApproximation(basis: PolynomialBasis, coefficients: tuple[complex, ...], domain: tuple[float, float] = (-1.0, 1.0), name: str = 'polynomial', max_error: float | None = None)An immutable polynomial produced independently of its evaluation DAG.
The coefficient convention is ascending degree. For basis="power",
while basis="chebyshev" means
domain=(a, b) records the physical interval used to design the approximation. The evaluator input is nevertheless normalized (a, b) == (-1, 1); the caller owns the affine map.
Attributes
basis: Basis in whichcoefficientsare expressed.coefficients: Ascending coefficients: entryimultiplies either or .domain: Plaintext interval on which the approximation was designed.name: Human-readable diagnostic name.max_error: Optional sampled or certified approximation error.
Attributes
| Name | Type | Default/value |
|---|---|---|
basis | PolynomialBasis | |
coefficients | tuple[complex, ...] | |
domain | tuple[float, float] | (-1.0, 1.0) |
name | str | 'polynomial' |
max_error | float | None | None |
degree
property
degree: intReturn the algebraic degree including trailing zero entries.
evaluate_plaintext
method
def evaluate_plaintext(values: np.ndarray) -> np.ndarray: ...Evaluate
values may have any NumPy-broadcastable shape, which is preserved in the output. They are coordinates in the polynomial's basis domain. For a Chebyshev approximation created on a physical interval other than
Radix2FourierTransformCompiler
class View source
Radix2FourierTransformCompiler(stage_count: int, imaginary_unit_correction: bool = False, scale_stage: int | None = None)Synthesize CKKS basis transforms from radix-2 butterflies.
Let coeffs_to_slots map and slots_to_coeffs map in the engine's cyclotomic slot order. The compiler's convention is
Consequently a plaintext round trip uses forward scale=1 and inverse scale=1/S. The supplied scale multiplies the numerical map; it is not a CKKS metadata scale and does not change the diagonal plaintext encoding scale selected later by the evaluator.
stage_count controls only algebraic layer collapse. A smaller value consumes fewer CKKS depths but materializes more diagonals in each stage; a larger value retains sparse butterflies but spends more depths. The choice of direct, BSGS, distributed, or custom execution remains independent. scale_stage places the transform's numerical factor in one selected stage; None uses the first forward or final inverse stage.
Attributes
| Name | Type | Default/value |
|---|---|---|
stage_count | int | |
imaginary_unit_correction | bool | False |
scale_stage | int | None | None |
compile
method
def compile(*, slots: int, direction: TransformDirection, generator: int, scale: float=1.0) -> tuple[DiagonalLinearTransform, ...]: ...Compile
Compilation proceeds in four steps:
- validate the cyclotomic slot orbit and build root tables;
- construct one three-diagonal transform per radix-2 layer;
- compose adjacent layers according to
stage_count; - fold
scaleinto the first forward stage or final inverse stage so the normalization is applied once in the complete transform.
slots is [slot]. generator must enumerate direction chooses complex128 stages in online execution order; compilation performs no encryption.