fhelium.algorithms.linear
Slot-wise linear transforms in cyclic-diagonal form.
A LinearTransform stores the diagonals torch.roll rotation convention. radix2_dft factors the CKKS coefficient/slot maps into such stages. BsgsPlan and DirectPlan select the evaluation schedule and report rotation steps. apply evaluates ordered stages; prepare encodes their diagonals and selects keys once so repeated apply calls and Compile capture only read the prepared materials.
A plan, built-in or custom, provides required_depths(stage), required_rotation_offsets(stage) and evaluate(arithmetic, ciphertext, stage, *, rotation_paths, rotate, encode_diagonal). rotation_paths maps each required offset to its selected primitive keys, rotate(value, offset) performs that rotation, and encode_diagonal(transform=, offset=, giant=, depth=, diagonal=) returns the NTT-domain plaintext of diagonal at the stage's fhelium.algorithms.Arithmetic.plaintext_scale, keyed by (transform, offset, giant) so preparation records it and prepared calls reuse it. With input depth required_depths(stage) with scale arithmetic.target_scales of that depth, two components and the input batch axes.
BsgsPlan
class View source
BsgsPlan(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', basis_conversion: 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' |
basis_conversion | 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: LinearTransform) -> int: ...Return the caller-selected BSGS step for one compiled transform.
schedule_for
method
def schedule_for(transform: LinearTransform) -> 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: LinearTransform) -> tuple[int, ...]: ...Return BSGS baby steps independently of decomposition sharing.
evaluate
method
def evaluate(arithmetic: Arithmetic, 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.
DirectPlan
class View source
DirectPlan()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: Arithmetic, 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.
LinearTransform
class View source
LinearTransform(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.
PreparedLinearTransform
class View source
PreparedLinearTransform(stages: tuple[LinearTransform, ...], plan: Any, output_scale: float | None)Encoded diagonals and selected rotation keys owned by the caller.
The object is produced by prepare for one input depth, scale and device. Passing it to apply reuses its materials without encoding; drop the object to release them.
Attributes
| Name | Type | Default/value |
|---|---|---|
stages | tuple[LinearTransform, ...] | |
plan | Any | |
output_scale | float | None |
apply
function View source
def apply(engine, ciphertext, transform: LinearTransform | Sequence[LinearTransform] | None=None, plan: Any=None, *, keys=None, prepared: PreparedLinearTransform | None=None, output_scale: float | None=None): ...Evaluate ordered stages
Each BSGS or direct stage multiplies encoded diagonals at plaintext scale output_scale for the last stage. The coefficient- domain input keeps two components and its batch axes. Without prepared, diagonals are encoded and keys selected from keys (default engine.keys) for this call; with prepared, its stages, plan, output scale and materials are used and keys is not consulted.
plan
function View source
def plan(transform: LinearTransform | Sequence[LinearTransform]) -> BsgsPlan: ...Return a BSGS plan with baby step
prepare
function View source
def prepare(engine, like, transform: LinearTransform | Sequence[LinearTransform], plan: Any=None, *, keys=None, output_scale: float | None=None) -> PreparedLinearTransform: ...Encode diagonals and select rotation keys for inputs with the state of like.
Keys are selected from keys, by default engine.keys. The preparation evaluates the stages once on like (any ciphertext with the intended depth, scale, batch shape and device); the encoding RNG advances once per diagonal. The result does not retain like.
radix2_dft
function View source
def radix2_dft(slots: int, *, direction: Literal['coeffs_to_slots', 'slots_to_coeffs'], stages: int, generator: int=5, scale: float=1.0, scale_stage: int | None=None, imaginary_unit_correction: bool=False) -> tuple[LinearTransform, ...]: ...Factor the CKKS map stages maps.
The stages balanced products in execution order. scale is folded into the first forward or last inverse stage, or into scale_stage when given, so the composed map equals scale times the unscaled transform with {direction}_stage_{i}.