fhelium.compile
Capture, transform, and execute reusable FHE computations.
The package carries one Program, its Tensor material bindings, caller-extensible CompileWorkspace, and ordered pass reports in a Compilation. The passes.lowering package maps CKKS operations to logical RNS/NTT composition in caller-composed pipelines. Frontend, CKKS, and lowering passes can stop at any represented IR abstraction level; callers may inspect or export that Program, continue through an external xDSL/MLIR pipeline, or bind backend resources. Low-level capture and Program transformation do not require live execution resources. The high-level compile function produces a lazily prepared CompiledCallable whose Backend supplies implementations and resources.
PrepareOperationOperandsPass
class View source
PrepareOperationOperandsPass(registry: OperationImplementationRegistry, resources: CkksDeviceResources | RnsContext | NttContext | Iterable[CkksDeviceResources | RnsContext | NttContext] = (), keys: Mapping[object, object] | Iterable[object] | EvaluationKeySet = (), name: str = 'prepare-operation-operands')Ask selected implementations for missing parameter Tensor requirements.
A Backend's optional tensor_requirements(operation, config) returns operation attributes and named material descriptions. This pass adds only missing operands; supplied Tensors, assignments, and existing symbols remain unchanged. Optional caller-supplied resources and keys populate missing entries in the current Compilation's material table through the shared preparation utility. No keys are generated. Implementations can defer requirements when execution facts are insufficient.
Attributes
| Name | Type | Default/value |
|---|---|---|
registry | OperationImplementationRegistry | |
resources | CkksDeviceResources | RnsContext | NttContext | Iterable[CkksDeviceResources | RnsContext | NttContext] | () |
keys | Mapping[object, object] | Iterable[object] | EvaluationKeySet | () |
name | str | 'prepare-operation-operands' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ArgumentSignature
class View source
ArgumentSignature(name: str, kind: str, properties: tuple[tuple[str, object], ...])Record one argument's type, layout, and represented value state.
Tensor contents and storage addresses are excluded. Immutable Python scalar values are included because capture may use them to construct the Program. The initial matcher conservatively requires equality of all recorded fields.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | |
kind | str | |
properties | tuple[tuple[str, object], ...] |
get
method
def get(name: str, default: object=None) -> object: ...Read one recorded property for a caller-selected pass pipeline.
CallSignature
class View source
CallSignature(arguments: tuple[ArgumentSignature, ...])Collect the conditions for one flat callable or Program invocation.
Attributes
| Name | Type | Default/value |
|---|---|---|
arguments | tuple[ArgumentSignature, ...] |
argument
method
def argument(name: str) -> ArgumentSignature: ...Return a named argument description.
CompiledCallable
class View source
CompiledCallable(source: Program | Compilation | Callable[_P, _R], *, backend: OperationBackend | None=None, pipeline: Pipeline | Callable[[CallSignature], Pipeline] | None=None, on_miss: Literal['compile', 'error']='compile', workspace: CompileWorkspace | None=None, inputs: Mapping[str, InputSpec] | None=None, material_names: Mapping[str, object] | None=None)Bases: Generic[_P, _R]
Prepare and repeatedly execute a Python function or Compile Program.
Construction does not capture, compile, allocate execution buffers, or run the computation. A first call prepares its input variant unless on_miss='error' requires prior prepare. Later calls reuse a linked executable when recorded input conditions match. No global capture context is installed, and compilation failures never silently execute Python.
pipeline is a complete caller-supplied pass sequence, or a function selecting one from a CallSignature. Omitting it selects dead-value removal, legal rotation hoisting, internal-transform reuse, and supported CUDA fusion while retaining native whole-operation routes. It does not insert rescaling or relinearization. Explicit pipelines replace that sequence rather than extending an implicit default.
backend=None uses the standard operation registry. Captured numerical data belongs to each Compilation's material_bindings. Capture may use several Engines as data providers; it does not establish an Engine owner or generate missing evaluation keys. Each specialization exposes the actual Backend selected for its transformed Program.
Inputs are flat Tensor/CKKS values and immutable scalar parameters. Capture supports pure Python functions, not async functions, methods, or arbitrary callable objects. A compiled helper is source-inlined during Eager capture; the outer pipeline and Backend govern its operations.
The top-level workspace and material binding dictionary are copied. Their materials and other custom mutable entries remain caller-owned and shared. Clear a callable after changing captured Python constants, and create a new one after changing a source Program or pass policy. Ordinary input Tensor contents may change without recompilation.
specializations
property
specializations: tuple[Specialization, ...]Return successfully linked variants in preparation order.
prepare
method
def prepare(*args: _P.args, **kwargs: _P.kwargs) -> Specialization: ...Capture, transform, and link this invocation without executing it.
Preparation is allowed with on_miss='error'. That option governs the callable's prepared-program cache, not a Backend compiler's kernel cache. Lazy Triton kernels may compile GPU binaries on the first actual call; execute representative warmup calls before timing or CUDA Graph capture. Material bindings and existing execution resources are supplied during linking; preparation neither generates evaluation keys nor executes the captured numerical computation.
with_backend
method
def with_backend(backend: OperationBackend) -> CompiledCallable[_P, _R]: ...Relink a snapshot of compiled variants against another Backend.
The returned callable starts without linked executables: call prepare first when on_miss='error'. Existing compilations retain their selected implementations and target/ABI assumptions. A changed Backend is not an instruction to silently reselect implementations or migrate machine code. New input signatures are prepared independently by each callable.
clear
method
def clear() -> None: ...Release this callable's variants without destroying caller resources.
Peers made with with_backend retain their previously shared compiled results. No allocator flush or resource mutation is performed.
Specialization
class View source
Specialization(backend: OperationBackend, executable: ProgramExecutable)Expose one prepared input variant, its Programs, and linked execution.
source precedes input-state specialization and optimization. compilation includes the selected Compile passes and their reports. backend is the selected implementation registry and resource workspace; it can also link the optimized Compilation directly. executable.manifest identifies the bound implementations/resources. Programs and workspace materials are inspectable; mutating them after preparation is not a supported way to update an existing callable.
Attributes
| Name | Type | Default/value |
|---|---|---|
backend | OperationBackend | |
executable | ProgramExecutable |
signature
property
signature: CallSignaturesource
property
source: Compilationcompilation
property
compilation: CompilationSpecializationMiss
class View source
SpecializationMiss()Bases: RuntimeError
Report that execution requires a specialization not prepared yet.
FuseOperationsPass
class View source
FuseOperationsPass(implementations: Sequence[FusionImplementation], min_ops: int = 2, name: str = 'fuse-operations')Select contiguous SSA regions using caller-supplied Backend support.
Implementations own operation, resource and layout admissibility. The pass grows a window while at least one supplied implementation accepts it, then selects the first matching implementation in caller order. An incompatible operation ends the current window without discarding compatible operations on either side. Recorded implementation assignments remain barriers, including assignments on plumbing operations.
Attributes
| Name | Type | Default/value |
|---|---|---|
implementations | Sequence[FusionImplementation] | |
min_ops | int | 2 |
name | str | 'fuse-operations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...SelectExecutionLoweringsPass
class View source
SelectExecutionLoweringsPass(implementations: OperationImplementationRegistry, fusion_implementations: Sequence[FusionImplementation] = (), lowerings: CkksLoweringRegistry = DEFAULT_CKKS_LOWERINGS, allow_partial_fusion: bool = True, name: str = 'select-execution-lowerings')Keep applicable whole operations or expose a supported fusion expression.
A supplied implementation assignment is local to its operation. Unassigned operations without whole-operation coverage require lowering. Where both routes exist, a detached lowering probe is accepted only when a fusion implementation supports the complete expression. With partial fusion enabled, supported subregions may instead be combined with independent implementations for the remaining operations.
Attributes
| Name | Type | Default/value |
|---|---|---|
implementations | OperationImplementationRegistry | |
fusion_implementations | Sequence[FusionImplementation] | () |
lowerings | CkksLoweringRegistry | DEFAULT_CKKS_LOWERINGS |
allow_partial_fusion | bool | True |
name | str | 'select-execution-lowerings' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...InitializeResourceBindingsPass
class View source
InitializeResourceBindingsPass(resources: ResourceBindings = field(default_factory=ResourceBindings), name: str = 'initialize-resource-bindings')Replace resource state left by an earlier build with this build's base.
Attributes
| Name | Type | Default/value |
|---|---|---|
resources | ResourceBindings | field(default_factory=ResourceBindings) |
name | str | 'initialize-resource-bindings' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...AssignImplementationsPass
class View source
AssignImplementationsPass(selections: Mapping[str, str] = field(default_factory=dict), overwrite: bool = False, name: str = 'assign-implementations')Attach requested implementation names to selected operation classes.
selections maps exact textual operation names to implementation names. Unselected operations and unknown mixed-level IR remain unchanged. The attribute is a backend build constraint; this pass neither discovers implementations nor asserts executable coverage.
Attributes
| Name | Type | Default/value |
|---|---|---|
selections | Mapping[str, str] | field(default_factory=dict) |
overwrite | bool | False |
name | str | 'assign-implementations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Annotate exact operation-name matches and report every assignment.
AssignNttImplementationPass
class View source
AssignNttImplementationPass(implementation: str | None = None, overwrite: bool = False, ntt_backend: str | None = None, algorithm: str | None = None, group_width: int | None = None, radix: int | None = None, name: str = 'assign-ntt-implementation')Assign a complete schedule or partial algorithm constraints.
Algorithm constraints apply to logical NTT operations and CKKS domain transitions. A concrete implementation applies to logical NTT operations; place this pass after CKKS lowering when assigning that implementation. Unspecified fields remain available to subsequent selection passes.
Attributes
| Name | Type | Default/value |
|---|---|---|
implementation | str | None | None |
overwrite | bool | False |
ntt_backend | str | None | None |
algorithm | str | None | None |
group_width | int | None | None |
radix | int | None | None |
name | str | 'assign-ntt-implementation' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...SelectNttImplementationsPass
class View source
SelectNttImplementationsPass(registry: OperationImplementationRegistry, name: str = 'select-ntt-implementations')Ask the selected NTT implementation to complete missing schedule choices.
Caller assignments and supplied Tensor operands remain authoritative. Missing transform tables become ordinary material references, whose data must be supplied separately. Operations with insufficient selection facts remain unchanged and report why their choice was deferred.
Attributes
| Name | Type | Default/value |
|---|---|---|
registry | OperationImplementationRegistry | |
name | str | 'select-ntt-implementations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...AssignCkksDepthsPass
class View source
AssignCkksDepthsPass(entry_depth: int | None = None)Assign depths and align add/sub joins after rescale placement.
Existing rescale nodes advance one public depth. At add/sub fan-in, only the lower-depth consumer edge is advanced through a real ModSwitchOp. Repeated application does not duplicate either transition.
Attributes
| Name | Type | Default/value |
|---|---|---|
entry_depth | int | None | None |
name | str | field(default='assign-ckks-depths', init=False) |
run
method
def run(compilation: 'Compilation') -> PassResult: ...AssignCkksScalesPass
class View source
AssignCkksScalesPass(entry_scale: float | None = None)Propagate actual scales through an already scheduled CKKS Program.
The pass never inserts arithmetic or metadata reinterpretation operations. Add/sub joins require exact binary64 scale equality. Rescale divides by the actual Q prime selected by its input depth.
Attributes
| Name | Type | Default/value |
|---|---|---|
entry_scale | float | None | None |
name | str | field(default='assign-ckks-scales', init=False) |
run
method
def run(compilation: 'Compilation') -> PassResult: ...BatchMode
type alias View source
BatchMode = Literal['none', 'any']CaptureError
class View source
CaptureError()Bases: CompileError, RuntimeError
Reject a source callable that the selected frontend cannot capture.
CapturedCallable
class View source
CapturedCallable(function: Callable[..., ReturnT], signature: inspect.Signature, input_specs: Mapping[str, InputSpec], fx_code: str)Bases: Generic[ReturnT]
Retain a Python callable as the pre-transform reference computation.
The full Python signature and input specifications record which arguments capture specialized as static values. reference restores those values before invoking function. fx_code is the captured PyTorch FX source retained for diagnostics. The transformed Program and CompileWorkspace belong to Compilation rather than this frontend record.
Attributes
| Name | Type | Default/value |
|---|---|---|
function | Callable[..., ReturnT] | |
signature | inspect.Signature | |
input_specs | Mapping[str, InputSpec] | |
fx_code | str |
runtime_signature
property
runtime_signature: inspect.SignatureReturn the callable signature after specialized static inputs.
reference
method
def reference(*args: object, **kwargs: object) -> ReturnT: ...Execute the captured callable with static inputs restored.
Compilation
class View source
Compilation(program: Program, workspace: CompileWorkspace = field(default_factory=CompileWorkspace), reports: tuple[PassReport, ...] = (), material_bindings: dict[str, torch.Tensor] = field(default_factory=dict))Carry one Program and the state accumulated while transforming it.
material_bindings maps Program symbols to live Tensor data. Every pass receives the current Compilation and uses this same dictionary. workspace holds caller inputs and pass-produced data that do not belong in portable IR. reports records the ordered pass history. A Pipeline returns a new Compilation with a transformed Program while retaining the same workspace and binding dictionary. Copy the dictionary when preparing independent assignments; copying it does not copy Tensor storage.
Attributes
| Name | Type | Default/value |
|---|---|---|
program | Program | |
workspace | CompileWorkspace | field(default_factory=CompileWorkspace) |
reports | tuple[PassReport, ...] | () |
material_bindings | dict[str, torch.Tensor] | field(default_factory=dict) |
prepare_material_bindings
function View source
def prepare_material_bindings(compilation: Compilation, *, resources: CkksDeviceResources | RnsContext | NttContext | Iterable[CkksDeviceResources | RnsContext | NttContext]=(), keys: Mapping[object, object] | Iterable[object] | EvaluationKeySet=()) -> tuple[str, ...]: ...Fill only missing bindings from supplied data providers and keys.
Descriptions guide this optional selection step. Named key entries matching a symbol or its label are direct assignments, without metadata checks. Semantic selection accepts one distinct candidate and leaves absent or ambiguous candidates unresolved. Existing bindings are never inspected or overwritten. The returned symbols remain unbound. No keys are generated.
CompileWorkspace
class View source
CompileWorkspace(values: Mapping[Any, Any] | None=None, /, **named_values: object)Bases: dict[object, object]
Store arbitrary entries shared across one Compile request.
Keys and values have no framework-defined schema. Code that uses an entry defines its format. Capture and every pass in the selected pipeline receive the same workspace.
CompileError
class View source
CompileError()Bases: Exception
Base error for the source-oriented compile package.
CompileInputError
class View source
CompileInputError()Bases: CompileError, ValueError
Reject a malformed source or frontend declaration.
CkksLoweringDefinition
class View source
CkksLoweringDefinition(name: str, operation_type: type[Operation], lower: CkksLowering, is_default: bool = False)Declare one named CKKS lowering beside its implementation.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | |
operation_type | type[Operation] | |
lower | CkksLowering | |
is_default | bool | False |
CkksLoweringRegistry
class View source
CkksLoweringRegistry(definitions: Sequence[CkksLoweringDefinition]=(), *, operation_specs: OperationSpecRegistry=DEFAULT_OPERATION_SPECS)Resolve implementation-local lowerings by operation class and name.
supports
method
def supports(operation: Operation) -> bool: ...Return whether one operation has a registered CKKS lowering.
definitions
property
definitions: tuple[CkksLoweringDefinition, ...]Return lowering declarations in registry order.
operation_types
property
operation_types: tuple[type[Operation], ...]Return CKKS operation classes with shared lowering definitions.
available
method
def available(operation_type: type[Operation]) -> tuple[str, ...]: ...Return registered lowering names for one operation class.
resolve
method
def resolve(operation_type: type[Operation], requested: str | None=None) -> CkksLoweringDefinition: ...Resolve a requested, default, or unambiguous lowering.
lower
method
def lower(operation: Operation, config: CkksConfig | None, compilation: Compilation, *, requested: str | None=None) -> LoweredCkksOperation: ...Apply one selected lowering without choosing an implementation.
DEFAULT_CKKS_LOWERINGS
constant View source
DEFAULT_CKKS_LOWERINGS = CkksLoweringRegistry((*ARITHMETIC_LOWERINGS, *REPRESENTATION_LOWERINGS, *KEY_SWITCH_LOWERINGS))DecisionRecord
class View source
DecisionRecord(subject: str, selected: str | None = None, candidates: tuple[str, ...] = (), details: tuple[str, ...] = ())Describe one inspectable choice made during a transformation.
Attributes
| Name | Type | Default/value |
|---|---|---|
subject | str | |
selected | str | None | None |
candidates | tuple[str, ...] | () |
details | tuple[str, ...] | () |
EliminateDeadValuesPass
class View source
EliminateDeadValuesPass(name: str = 'eliminate-dead-values')Erase unused operations according to registered effects.
The pass handles high-level CKKS, lowered RNS/NTT, and pure fusion regions. It enters known structured regions, preserving their terminators and result interfaces. Unknown operations/regions, random draws, mutation, and opaque effects remain roots. Registration must name the exact operation class; inheriting a Pure trait does not grant an extension permission to disappear.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'eliminate-dead-values' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Walk blocks in reverse dependency order and remove dead producers.
ReuseIntermediatesPass
class View source
ReuseIntermediatesPass(name: str = 'reuse-intermediates')Remove duplicate references/casts and share internal transform results.
Transform reuse requires the same SSA operands, result types, and attributes. A mutation, random draw, unknown operation, or region ends a local reuse run. Directly returned results, views that escape, and unknown consumers prevent reuse so this pass does not merge independently observable output storage. It does not cancel approximate arithmetic or move rounding across sums.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'reuse-intermediates' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...EmitBackendPythonPass
class View source
EmitBackendPythonPass(registry: OperationImplementationRegistry | None = None, entry_point: str = 'generated_backend', name: str = 'emit-backend-python')Publish direct Backend Python for the Program at this pass position.
Attributes
| Name | Type | Default/value |
|---|---|---|
registry | OperationImplementationRegistry | None | None |
entry_point | str | 'generated_backend' |
name | str | 'emit-backend-python' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...EmitEagerPythonPass
class View source
EmitEagerPythonPass(entry_point: str = 'generated_eager', name: str = 'emit-eager-python')Publish Eager-style Python for the CKKS Program at this pass position.
Attributes
| Name | Type | Default/value |
|---|---|---|
entry_point | str | 'generated_eager' |
name | str | 'emit-eager-python' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...BackendPythonSource
class View source
BackendPythonSource(source: str, entry_point: str, input_names: tuple[str, ...], material_symbols: tuple[str, ...], resource_symbols: tuple[str, ...], operation_count: int, resource_requirements: tuple[tuple[str, str], ...] = ())Bases: GeneratedPythonSource
Python source expressed through resolved Backend implementation calls.
Attributes
| Name | Type | Default/value |
|---|---|---|
resource_requirements | tuple[tuple[str, str], ...] | () |
EagerPythonSource
class View source
EagerPythonSource(source: str, entry_point: str, input_names: tuple[str, ...], material_symbols: tuple[str, ...], resource_symbols: tuple[str, ...], operation_count: int)Bases: GeneratedPythonSource
Python source expressed through the public Eager Engine API.
GeneratedPythonSource
class View source
GeneratedPythonSource(source: str, entry_point: str, input_names: tuple[str, ...], material_symbols: tuple[str, ...], resource_symbols: tuple[str, ...], operation_count: int)Hold editable Python source and its external symbol interface.
Attributes
| Name | Type | Default/value |
|---|---|---|
source | str | |
entry_point | str | |
input_names | tuple[str, ...] | |
material_symbols | tuple[str, ...] | |
resource_symbols | tuple[str, ...] | |
operation_count | int |
RotationHoistingPass
class View source
RotationHoistingPass(max_group_size: int | None = None, name: str = 'rotation-hoisting')Share preparation among rotations of the same ciphertext data.
A rotation has the form Finish(c0, Prepare(c1, tables), key, step). Rotations with the same input SSA value, parameter operands, and compatible attributes can share Prepare despite interleaved consumers or rotations of other inputs. The emitted RotateManyOp retains each key operand, result type, and rotation step. Its common output domain and execution attributes must agree across the group.
Matching and placement stay inside a block's known-pure effect interval. Unknown operations, effects, control flow, and assigned implementations end that interval; known nested regions are processed independently. Every group is placed after its computed operands and before its first result use. Material references may move within the interval, but producer computations are not speculated or reordered.
max_group_size bounds the number of results produced together. Grouping can extend result lifetimes.
Attributes
| Name | Type | Default/value |
|---|---|---|
max_group_size | int | None | None |
name | str | 'rotation-hoisting' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Identify compatible rotations and place legal multi-result groups.
InputSpec
class View source
InputSpec(role: ValueRole, depth: int = 0, scale: float | None = None, slots: SlotExtent = 'full', batch_mode: BatchMode = 'none', polynomial_domain: PolynomialDomainSpec | None = None, residue_representation: ResidueRepresentationSpec | None = None, static_value: StaticValue = None)Declare one function input's role in the PyTorch-to-FHE interface.
encrypted declares a logical slot extent, batch policy, depth, and scale for a runtime Tensor or core Ciphertext. message declares public Python/PyTorch data passed through directly until an plaintext-preparation operation consumes it. plaintext declares a caller-owned core Plaintext whose state is validated at its encrypted consumer. static declares an immutable scalar specialized during capture and removed from the Program's runtime argument list.
Attributes
| Name | Type | Default/value |
|---|---|---|
role | ValueRole | |
depth | int | 0 |
scale | float | None | None |
slots | SlotExtent | 'full' |
batch_mode | BatchMode | 'none' |
polynomial_domain | PolynomialDomainSpec | None | None |
residue_representation | ResidueRepresentationSpec | None | None |
static_value | StaticValue | None |
InsertMultiplyNttTransitionsPass
class View source
InsertMultiplyNttTransitionsPass(name: str = 'insert-multiply-ntt-transitions')Insert typed CKKS NTT transitions at registered logical multiplies.
The transformed operand type records NTT/Montgomery state, so repeated application is idempotent without a marker attribute. Unrealized casts preserve visible type-changing edges from logical values to CKKS values.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'insert-multiply-ntt-transitions' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Insert missing transitions or return a legal no-op report.
InsertPlaintextPreparationPass
class View source
InsertPlaintextPreparationPass(name: str = 'insert-plaintext-preparation')Insert typed plaintext preparation at registered mixed logical ops.
Existing CKKS plaintext operands make repeated application a legal no-op. The visible unrealized cast on the ciphertext edge records the still-open logical-to-CKKS type conversion without mutating its producer.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'insert-plaintext-preparation' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Prepare supported public operands across all function blocks.
InsertRelinearizationPass
class View source
InsertRelinearizationPass(name: str = 'insert-relinearization')Relinearize each CT3 multiplication before its first non-transition use.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'insert-relinearization' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...InsertRescalePass
class View source
InsertRescalePass(name: str = 'insert-rescale')Rescale each multiplication before its first non-transition use.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'insert-rescale' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...LateRelinearizationPass
class View source
LateRelinearizationPass(name: str = 'late-relinearization')Coalesce compatible CT3 add/sub/negate regions before relinearization.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'late-relinearization' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...LateRescalePass
class View source
LateRescalePass(name: str = 'late-rescale')Coalesce compatible add/sub/negate regions before rescaling.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'late-rescale' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...LowerCkksToRnsNttPass
class View source
LowerCkksToRnsNttPass(selections: Mapping[str, str] = field(default_factory=dict), preserve: frozenset[str] = frozenset(), registry: CkksLoweringRegistry = DEFAULT_CKKS_LOWERINGS)Apply caller-selected CKKS-to-RNS/NTT lowering definitions.
Attributes
| Name | Type | Default/value |
|---|---|---|
selections | Mapping[str, str] | field(default_factory=dict) |
preserve | frozenset[str] | frozenset() |
registry | CkksLoweringRegistry | DEFAULT_CKKS_LOWERINGS |
name | str | field(default='lower-ckks-to-rns-ntt', init=False) |
run
method
def run(compilation: 'Compilation') -> PassResult: ...LoweredCkksOperation
class View source
LoweredCkksOperation(operations: tuple[Operation, ...], result: SSAValue, material_descriptions: dict[str, dict[str, object]] = field(default_factory=dict))Hold replacement operations and the logical result of one CKKS op.
Attributes
| Name | Type | Default/value |
|---|---|---|
operations | tuple[Operation, ...] | |
result | SSAValue | |
material_descriptions | dict[str, dict[str, object]] | field(default_factory=dict) |
LowerLogicalToCkksPass
class View source
LowerLogicalToCkksPass(name: str = 'lower-logical-to-ckks')Lower registered logical arithmetic through visible typed CKKS edges.
Unrealized conversion casts preserve mixed-level result types for consumers that have not been lowered. Locally unresolved patterns remain legal no-ops and leave their original operations unchanged with diagnostics.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'lower-logical-to-ckks' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Lower locally ready registered operations and report blockers.
LowerMessagePlaintextPreparationPass
class View source
LowerMessagePlaintextPreparationPass(name: str = 'lower-message-plaintext-preparation')Expand concrete message preparation into visible CKKS operations.
Depth, scale, ordered prime ids, and modulus basis must already be assigned by a caller-selected CKKS scheduling pass. Missing state is an error rather than a request for this pass to choose a depth or scale.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'lower-message-plaintext-preparation' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...LowerSemanticToLogicalPass
class View source
LowerSemanticToLogicalPass(name: str = 'lower-semantic-to-logical')Classify registered encrypted semantic operations by operand roles.
Other dialects, public-only arithmetic, malformed operations, and unknown value roles remain structurally intact so partial mixed-level Programs stay valid inputs and outputs of the pass.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'lower-semantic-to-logical' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Lower matching operation classes and report unchanged candidates.
LinkProgramPass
class View source
LinkProgramPass(name: str = 'link-backend-program')Match all external references and produce the Program executable.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'link-backend-program' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...PlanningError
class View source
PlanningError()Bases: CompileError, RuntimeError
Report that a selected transform cannot make its requested decision.
Pass
class View source
Pass()Bases: Protocol
Define one locally applicable transformation or analysis step.
name
property
name: strStable name used in pipeline composition and reports.
run
method
def run(compilation: Compilation, /) -> PassResult: ...Inspect or transform the current Compilation and report the outcome.
PassReport
class View source
PassReport(name: str, stats: PassStats, diagnostics: tuple[str, ...] = (), decisions: tuple[DecisionRecord, ...] = ())Record one pass's activity, diagnostics, and choices.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | |
stats | PassStats | |
diagnostics | tuple[str, ...] | () |
decisions | tuple[DecisionRecord, ...] | () |
PassResult
class View source
PassResult(program: Program, stats: PassStats = PassStats(), diagnostics: tuple[str, ...] = (), decisions: tuple[DecisionRecord, ...] = ())Program, counts, diagnostics, and choices returned by one pass.
Attributes
| Name | Type | Default/value |
|---|---|---|
program | Program | |
stats | PassStats | PassStats() |
diagnostics | tuple[str, ...] | () |
decisions | tuple[DecisionRecord, ...] | () |
changed
property
changed: boolWhether the reported counts describe an IR change.
unchanged
method
def unchanged(program: Program, *, matched: int=0, skipped: int=0, diagnostics: tuple[str, ...]=(), decisions: tuple[DecisionRecord, ...]=()) -> PassResult: ...Record a normal pass result that preserves the Program.
PassStats
class View source
PassStats(matched: int = 0, transformed: int = 0, inserted: int = 0, removed: int = 0, skipped: int = 0)Count one pass's observed and changed patterns.
Attributes
| Name | Type | Default/value |
|---|---|---|
matched | int | 0 |
transformed | int | 0 |
inserted | int | 0 |
removed | int | 0 |
skipped | int | 0 |
Pipeline
class View source
Pipeline(passes: tuple[Pass, ...] = ())Run an ordered, dependency-free tuple of partial transformations.
Attributes
| Name | Type | Default/value |
|---|---|---|
passes | tuple[Pass, ...] | () |
names
property
names: tuple[str, ...]Return pass names in execution order.
run
method
def run(compilation: Compilation) -> Compilation: ...Clone and transform one Compilation while retaining its workspace.
then
method
def then(*passes: Pass) -> Pipeline: ...Append passes in order.
before
method
def before(target: str, *passes: Pass) -> Pipeline: ...Insert passes before one uniquely named pass.
after
method
def after(target: str, *passes: Pass) -> Pipeline: ...Insert passes after one uniquely named pass.
replace
method
def replace(target: str, *passes: Pass) -> Pipeline: ...Replace one uniquely named pass.
PythonCodegenError
class View source
PythonCodegenError()Bases: RuntimeError
Report that a Python emitter cannot represent the scanned Program.
MaterializeResourcesPass
class View source
MaterializeResourcesPass(materializer: ResourceMaterializer, name: str = 'materialize-backend-resources')Create missing constructible resources once for the whole Program.
Attributes
| Name | Type | Default/value |
|---|---|---|
materializer | ResourceMaterializer | |
name | str | 'materialize-backend-resources' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ResolveBackendOperationsPass
class View source
ResolveBackendOperationsPass(registry: OperationImplementationRegistry, in_place: bool = False, name: str = 'resolve-backend-operations')Require Backend support and build the Program dispatch table.
Attributes
| Name | Type | Default/value |
|---|---|---|
registry | OperationImplementationRegistry | |
in_place | bool | False |
name | str | 'resolve-backend-operations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ResolveTensorPlaceholdersPass
class View source
ResolveTensorPlaceholdersPass(name: str = 'resolve-tensor-placeholders')Supply available Tensors while leaving missing references unresolved.
The pass performs no allocation, generation or callback. Callers can run it with a partial table; linking checks references that are still required.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'resolve-tensor-placeholders' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ValidateExecutionRepresentationsPass
class View source
ValidateExecutionRepresentationsPass(name: str = 'validate-execution-representations')Require concrete legal representations at fixed executable ABIs.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'validate-execution-representations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ResolveRotationKeyOperandsPass
class View source
ResolveRotationKeyOperandsPass()Replace logical rolls with CKKS rotations bound to named key resources.
The pass normalizes each step using the CKKS slot count and names its resource rotation-key:<step>. It reads CkksConfig from the Compile workspace and records the resolved coefficient automorphism on the key operand. It writes symbolic references only; key creation and live binding remain caller responsibilities.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | field(default='resolve-rotation-key-operands', init=False) |
run
method
def run(compilation: 'Compilation') -> PassResult: ...SlotExtent
data View source
SlotExtent = int | Literal['full']StaticValue
data View source
StaticValue = bool | int | float | complex | str | NoneSvgGraphDirection
type alias View source
SvgGraphDirection = Literal['TB', 'BT', 'LR', 'RL']SvgGraphError
class View source
SvgGraphError()Bases: RuntimeError
Report that Program SVG rendering could not complete.
SvgGraphField
type alias View source
SvgGraphField = Literal['name', 'opcode', 'role', 'operands', 'result_types', 'attributes', 'num_users']SvgGraphOutput
class View source
SvgGraphOutput(path: Path, temporary: bool)Record the SVG file produced by a visualization pass.
Attributes
| Name | Type | Default/value |
|---|---|---|
path | Path | |
temporary | bool |
SvgGraphPresentation
class View source
SvgGraphPresentation(*, fields: Collection[SvgGraphField] | None=None, attribute_names: Collection[str] | None=None, attribute_preview_chars: int | None=180, theme: SvgGraphTheme | None=None)Select and format operation details for an SVG graph.
The presentation is independent of graph traversal and file production. Subclasses can override select_attributes for filtering, format_attribute_value for one-value display policy, operation_sections for complete operation-row transformation, or operation_tooltip for aggregate hover details. These methods must not mutate their operation or Program.
select_attributes
method
def select_attributes(operation: Operation) -> tuple[tuple[str, Attribute], ...]: ...Return sorted non-internal attributes selected for operation.
format_attribute_value
method
def format_attribute_value(operation: Operation, name: str, attribute: Attribute) -> str: ...Format one selected attribute for its character-limited preview.
operation_sections
method
def operation_sections(context: SvgOperationContext) -> tuple[SvgNodeSection, ...]: ...Return all displayed record rows for one operation.
Override this complete-row hook to reorder, rename, remove, or inject derived sections while reusing super().operation_sections(context).
operation_tooltip
method
def operation_tooltip(context: SvgOperationContext, sections: Collection[SvgNodeSection]) -> str | None: ...Return one aggregate node tooltip from already-rendered sections.
SvgGraphTheme
class View source
SvgGraphTheme(*, operation_palette: Collection[str] | None=None, operation_colors: Mapping[str, str] | None=None, operation_color_key: Callable[[SvgOperationContext], str] | None=None, canvas_color: str='transparent', input_fill_color: str='#DCE4FF', output_fill_color: str='#F3D89D', node_font_color: str='#181B26', node_stroke_color: str='#596178', edge_color: str='#7B8193')Define colors and operation color classification for an SVG graph.
An operation first receives a key from operation_color_key. A matching operation_colors entry wins; otherwise the key is deterministically mapped into operation_palette. The hash implementation is private, but equal keys under one theme always receive equal colors. None selects the FHElium default palette or color-key function. operation_colors=None uses the default constant color, while an empty mapping removes it. Theme configuration is read-only and deliberately unhashable because a caller-supplied color-key callable does not define a general cache identity.
Attributes
| Name | Type | Default/value |
|---|---|---|
operation_palette | tuple[str, ...] | |
operation_colors | Mapping[str, str] | |
operation_color_key | Callable[[SvgOperationContext], str] | |
canvas_color | str | |
input_fill_color | str | |
output_fill_color | str | |
node_font_color | str | |
node_stroke_color | str | |
edge_color | str |
operation_fill_color
method
def operation_fill_color(context: SvgOperationContext) -> str: ...Return the configured or stable palette color.
SvgGraphVisualizationPass
class View source
SvgGraphVisualizationPass(output_path: str | PathLike[str] | None=None, *, overwrite: bool=False, entry: str='main', presentation: SvgGraphPresentation | None=None, rank_direction: SvgGraphDirection='TB', name: str='visualize-svg')Render one Program function to a local or temporary SVG file.
output_path selects a caller-owned local path. When it is omitted, the pass creates a unique directory under the operating system's temporary location. In both cases, SvgGraphOutput records the produced file in the Compilation workspace.
Attributes
| Name | Type | Default/value |
|---|---|---|
output_path | Path | None | |
overwrite | bool | |
entry | str | |
presentation | SvgGraphPresentation | None | |
rank_direction | SvgGraphDirection | |
name | str |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Render the current Program and publish its output path.
SvgNodeSection
class View source
SvgNodeSection(name: str, value: str, tooltip: str | None = None)Represent one labeled record row inside an SVG operation node.
value participates in Graphviz layout. tooltip optionally adds complete or alternate details for the containing node's aggregate hover text; Graphviz does not attach a separate tooltip to each record cell.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | |
value | str | |
tooltip | str | None | None |
SvgOperationContext
class View source
SvgOperationContext(operation: Operation, result_names: tuple[str, ...], operand_names: tuple[str, ...])Provide stable operation data to an SVG presentation policy.
Attributes
| Name | Type | Default/value |
|---|---|---|
operation | Operation | |
result_names | tuple[str, ...] | |
operand_names | tuple[str, ...] |
opcode
property
opcode: strReturn the registered or dynamic operation name.
TransformError
class View source
TransformError()Bases: RuntimeError
Report a malformed Compile transformation request or result.
backend_linking_pipeline
function View source
def backend_linking_pipeline(backend: OperationBackend, *, in_place: bool=False) -> Pipeline: ...Return the standard Backend linking sequence as an editable Pipeline.
capture
function View source
def capture(function: Callable[..., ReturnT], *, inputs: Mapping[str, InputSpec], workspace: CompileWorkspace | None=None, material_names: Mapping[str, object] | None=None) -> Compilation: ...Trace a Python callable into a neutral mixed-dialect Program.
inputs declares every parameter's encrypted, message, plaintext, or static role. Capture specializes static values, records Tensor constants as symbolic materials in Compilation.material_bindings, lowers recognized arithmetic to semantic FHElium operations, and preserves other FX calls as torch.call operations. The returned Compilation carries that Program and workspace; a CapturedCallable workspace entry retains the source callable as the pre-transform reference. Pure-public, mixed-level, and partially lowered graphs remain valid frontend results. Runtime binding and execution are not performed by this package.
capture_eager
function View source
def capture_eager(function: Callable[..., object], *, arguments: Mapping[str, object], workspace: CompileWorkspace | None=None, material_names: Mapping[str, object] | None=None) -> Compilation: ...Capture a Python function as mixed public Tensor and encrypted dataflow.
Runtime Tensor, ciphertext, plaintext and key arguments become SSA inputs. Python scalars are static parameters. Ordinary Tensor arithmetic remains ordinary Torch calls; encrypted numerical operators become semantic FHE operations. Supported Engine calls retain their concrete CKKS transitions and actual key/table Tensor operands. Capture does not encrypt public inputs or generate keys. Missing evaluation keys remain material placeholders.
Fixed Tensor/value references, including nested list/tuple/dict containers, become live material bindings. Their contents are not constant-folded. Numerical data is never executed during capture: ordinary Tensor metadata is propagated with FakeTensor kernels. Explicit Engine codec preparation becomes runtime operations with advancing rounding state.
The original function is retained as the source reference. Function-backed compiled helpers are source-inlined under the outer compilation choices. Static Python control flow and structured outputs are supported. Data-based Python branching, in-place operations and arbitrary callable objects require other frontend or manual Program support; no capture fallback is attempted.
compile
function View source
def compile(source: Program | Compilation | Callable[_P, _R] | None=None, *, backend: OperationBackend | None=None, pipeline: Pipeline | Callable[[CallSignature], Pipeline] | None=None, on_miss: Literal['compile', 'error']='compile', workspace: CompileWorkspace | None=None, inputs: Mapping[str, InputSpec] | None=None, material_names: Mapping[str, object] | None=None) -> CompiledCallable[_P, _R] | Callable[[Callable[_P, _R]], CompiledCallable[_P, _R]]: ...Create a lazily prepared callable or decorate a pure Python function.
Python functions capture ordinary Tensor expressions and Eager calls in one Program unless inputs selects the role-declared FX frontend. Ordinary Tensor computations retain their public numerical role; a Ciphertext input does not encrypt other inputs or the entire function. Programs and Compilations skip Python capture. There is no frontend fallback: unsupported capture or execution raises. The original Python reference and standard function metadata are retained.
An omitted Backend uses the standard operation registry. Capture retains actual Tensor materials; it does not bind an Engine owner or generate keys. material_names assigns stable symbols to fixed Tensor/value objects.
When pipeline is omitted, preparation uses default_lower_and_fuse_pipeline. A supplied Pipeline, or function from CallSignature to Pipeline, replaces that recipe rather than extending it. on_miss='error' requires prepare before calls with new input conditions or new Backend bindings. Lazy Backend kernel compilation may still occur on the first actual execution.
Use capture, capture_eager, Compilation, and Pipeline.run when a transformed Program rather than a callable executable is the desired product. Those lower-level operations do not require a Backend.
default_svg_operation_color_key
function View source
def default_svg_operation_color_key(context: SvgOperationContext) -> str: ...Return the default stable operation color key.
Operation names define ordinary keys. Preserved torch.call operations additionally include call kind and target so custom classifiers can delegate without reproducing that rule.
encrypted
function View source
def encrypted(*, depth: int=0, scale: float | None=None, slots: SlotExtent='full', batch_mode: BatchMode='none', polynomial_domain: PolynomialDomainSpec | None=None, residue_representation: ResidueRepresentationSpec | None=None) -> InputSpec: ...Declare a secret slot input accepted as Tensor or Ciphertext.
depth and a non-None scale define the runtime CKKS input state; scale=None selects the execution Engine's default scale. slots specifies either the engine's full capacity or a final-axis extent. batch_mode='none' requires a one-dimensional Tensor and an unbatched Ciphertext; 'any' permits leading batch axes.
polynomial_domain and residue_representation may jointly declare a coefficient/standard or NTT/Montgomery input contract; omitting both leaves representation assignment to later passes.
These fields are frontend metadata. Later transforms and runtimes may use, refine, ignore, or diagnose them according to caller-selected policy. The callable retained by CapturedCallable.reference consumes its ordinary public Tensor argument.
lower_ckks_program
function View source
def lower_ckks_program(compilation, config: CkksConfig | None, *, registry: CkksLoweringRegistry=DEFAULT_CKKS_LOWERINGS, selections: Mapping[str, str] | None=None, preserve: Collection[str]=()) -> _LoweringResult: ...Apply selected CKKS lowerings while preserving other mixed-level IR.
message
function View source
def message() -> InputSpec: ...Declare public Tensor/scalar data processed by ordinary PyTorch.
Message-only subgraphs execute as public calls. A mixed encrypted operation introduces operation-specific encoding and plaintext preparation; that preparation derives the required CKKS representation from its ciphertext consumer.
plaintext
function View source
def plaintext() -> InputSpec: ...Declare a caller-owned FHElium Plaintext with runtime state.
Capture records this role without requiring a live core Plaintext. Runtime binding and state analysis are separate consumers. The callable used by CapturedCallable.reference consumes the public Tensor or scalar shadow supplied by the caller.
static
function View source
def static(value: StaticValue) -> InputSpec: ...Specialize an immutable scalar Python input during capture.
A finite bool, int, float, complex, str, or None value participates in Python control and graph construction. Capture stores its serialized value in Program metadata and removes the parameter from CapturedCallable.runtime_signature and Program execution inputs.