fhelium.compile
Capture, transform, specialize, and link computations for reusable execution.
A Compilation carries a Program, Tensor material bindings, a shared CompileWorkspace, and ordered pass reports. Pipeline composes analyses and transformations; Backend linking prepares the result for execution. The compile entry point creates a CompiledCallable with a cache of input specializations.
AggregateRotationSumsPass
class View source
AggregateRotationSumsPass(combine_rescale: bool = True, name: str = 'aggregate-rotation-sums')Replace compatible rotation/add trees with a shared QP quotient.
Including this pass is the caller's choice to change intermediate CKKS rounding. Matching uses SSA values and represented state. Independent intermediate users are preserved. Unknown effects, caller assignments, mismatched tables/state or partial required facts leave the region unchanged.
combine_rescale also recognizes uniformly rescaled inputs and divides the aggregate by P times the complete dropped Q group. Otherwise each original input rescale remains before the aggregate key switching.
Measured on RTX PRO 6000 Blackwell Server Edition: 128x128 @ 128x8 BSGS matrices, baby step 8, N=16384, Q=8, P=1, int64 residues, scale 2^40. Latencies include device synchronization, using resident inputs; values are medians of three process medians, with 30 samples per process.
| Execution / implementation | Matrix | Baseline (ms) | Aggregate (ms) |
|---|---|---|---|
| CUDA Graph / default fusion | PT x CT | 9.947 | 8.539 |
| CUDA Graph / default fusion | CT x CT | 17.901 | 16.444 |
| No Graph / whole operation | PT x CT | 12.702 | 11.835 |
| No Graph / whole operation | CT x CT | 21.132 | 25.383 |
Both matrix workloads improved with Graph replay. Without Graph, PT x CT improved, but CT x CT became 20.1% slower.
Attributes
| Name | Type | Default/value |
|---|---|---|
combine_rescale | bool | True |
name | str | 'aggregate-rotation-sums' |
run
method
def run(compilation): ...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. Reuse 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.
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 updates represented scale metadata while preserving the arithmetic operations. Add/sub joins require equal binary64 scales. Rescale divides the input scale by config.rescale_divisor(depth), the product of the dropped Q group.
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: ...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 registered textual operation names to implementation names. Matching uses full-name equality. Unselected operations remain unchanged. The resulting attributes constrain subsequent Backend resolution, which checks implementation availability.
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 matching operation names and report each 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: ...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], ...] | () |
BatchMode
type alias View source
BatchMode = Literal['none', 'any']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.
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.
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.
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.
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 a Program, its bindings, workspace, and transformation reports.
material_bindings maps Program symbols to live Tensors. workspace carries caller inputs and pass-produced Python data; reports records the ordered pass history. Pipeline execution returns a new Compilation with the transformed Program and shares the workspace and binding dictionary across its passes.
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) |
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.
CompileWorkspace
class View source
CompileWorkspace(values: Mapping[Any, Any] | None=None, /, **named_values: object)Bases: dict[object, object]
Store shared entries for one compilation request.
Each consumer defines the format of its entries. Capture and every pass in the selected pipeline receive the same workspace.
CompiledCallable
class View source
CompiledCallable(source: Program | Compilation | Callable[_P, _R], *, backend: OperationBackend | None=None, resources: CkksDeviceResources | RnsContext | NttContext | Iterable[CkksDeviceResources | RnsContext | NttContext]=(), keys: Mapping[object, object] | Iterable[object] | EvaluationKeySet=(), 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]
A callable that caches input-specialized executables for one source computation.
prepare creates and links a specialization for given arguments. Calls reuse a matching executable; a cache miss prepares a new specialization by default, or raises SpecializationMiss when on_miss='error'. clear releases the cached specializations.
specializations
property
specializations: tuple[Specialization, ...]Return successfully linked variants in preparation order.
prepare
method
def prepare(*args: _P.args, **kwargs: _P.kwargs) -> Specialization: ...Prepare and return the specialization matching these arguments.
Preparation captures the source when needed, runs its selected pipeline, and links the resulting Program. A matching cached specialization is returned directly. This method populates the cache under either on_miss policy.
Device-kernel compilation may occur on first execution after linking. Warm representative calls before measuring steady-state execution or capturing device launches.
with_backend
method
def with_backend(backend: OperationBackend) -> CompiledCallable[_P, _R]: ...Relink a snapshot of compiled variants against another Backend.
Call prepare to link the returned callable before execution when on_miss='error'. Existing compilations retain their selected implementations and target/ABI requirements, which the new Backend must satisfy. Each callable prepares new input signatures independently.
clear
method
def clear() -> None: ...Release this callable's specialization cache.
Call this after changing captured Python constants so the next preparation captures their new values. Changes to input Tensor contents reuse the existing specialization while its recorded input conditions hold. Caller resources and compiled results retained by peers made with with_backend remain live.
DEFAULT_CKKS_LOWERINGS
constant View source
DEFAULT_CKKS_LOWERINGS = CkksLoweringRegistry((*ARITHMETIC_LOWERINGS, *REPRESENTATION_LOWERINGS, *KEY_SWITCH_LOWERINGS, *ROTATION_SUM_LOWERINGS, *MODULUS_RAISE_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, ...] | () |
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.
EliminateDeadValuesPass
class View source
EliminateDeadValuesPass(name: str = 'eliminate-dead-values')Erase unused operations according to registered effects.
The pass traverses known structured regions while preserving terminators and result interfaces. Unknown operations or regions, random draws, mutation, and opaque effects remain liveness roots. Removal requires purity registered for the operation's concrete class; an inherited Pure trait alone is insufficient.
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.
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: ...FuseOperationsPass
class View source
FuseOperationsPass(implementations: Sequence[FusionImplementation], min_ops: int = 2, name: str = 'fuse-operations')Group pure SSA dependencies using caller-supplied Backend support.
Independent pure work can be scheduled around a supported region. Effects, opaque operations and caller implementation assignments preserve their order. Implementations determine operation, parameter and layout support.
Attributes
| Name | Type | Default/value |
|---|---|---|
implementations | Sequence[FusionImplementation] | |
min_ops | int | 2 |
name | str | 'fuse-operations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...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 |
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: ...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: ...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: ...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: ...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.
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) |
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: ...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 a tuple of transformations in caller-specified order.
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.
PlanningError
class View source
PlanningError()Bases: CompileError, RuntimeError
Report that a selected transform cannot make its requested decision.
ResolveMaterialRequirementsPass
class View source
ResolveMaterialRequirementsPass(registry: OperationImplementationRegistry | None = None, key_layouts: Mapping[str, Mapping[str, object]] = field(default_factory=dict), name: str = 'resolve-material-requirements')Resolve key layouts and implementation material operands across a Program.
The registry defaults to the Compilation workspace. key_layouts adds caller layout declarations keyed by material symbol or label. Existing operands and compatible metadata are retained; insufficient facts leave the corresponding requirements unresolved.
Attributes
| Name | Type | Default/value |
|---|---|---|
registry | OperationImplementationRegistry | None | None |
key_layouts | Mapping[str, Mapping[str, object]] | field(default_factory=dict) |
name | str | 'resolve-material-requirements' |
run
method
def run(compilation: Compilation) -> PassResult: ...PythonCodegenError
class View source
PythonCodegenError()Bases: RuntimeError
Report that a Python emitter cannot represent the scanned Program.
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: ...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: ...ResolveTensorPlaceholdersPass
class View source
ResolveTensorPlaceholdersPass(name: str = 'resolve-tensor-placeholders')Bind Program Tensor references from a symbol-to-Tensor table.
A partial table resolves the symbols it contains and leaves other references unchanged. Linking checks the references still required for execution.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'resolve-tensor-placeholders' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...ReuseIntermediatesPass
class View source
ReuseIntermediatesPass(name: str = 'reuse-intermediates')Share internal pure computations while preserving observable output storage.
Reuse requires the same concrete operation, ordered SSA operands, result types, attributes and properties. Numerical materials are ordinary operands and must therefore match by SSA identity. A mutation, random draw, unknown operation, region or implementation assignment ends a local reuse run.
Shared results must reach only fresh out-of-place readers, possibly through views. Direct returns, escaping views and unknown or assigned consumers prevent sharing. This preserves independently observable result storage without changing arithmetic order, rounding or value-state transitions.
Attributes
| Name | Type | Default/value |
|---|---|---|
name | str | 'reuse-intermediates' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...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.
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', execution_cost: Callable[[Operation, Sequence[Operation]], tuple[float, float] | None] | None = None)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, an isolated 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.
execution_cost may compare the whole operation with the isolated lowered candidate after this pass's fusion scheduling. It returns (whole, lowered) costs in one caller-selected unit, or None when the comparison is unknown. Lowering is selected only for a strictly smaller supplied cost; ties retain the whole operation. Missing estimates retain the fusion-coverage decision. Implementation assignments always take precedence over this callback.
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' |
execution_cost | Callable[[Operation, Sequence[Operation]], tuple[float, float] | None] | None | None |
run
method
def run(compilation: 'Compilation') -> PassResult: ...SelectNttImplementationsPass
class View source
SelectNttImplementationsPass(registry: OperationImplementationRegistry | None = None, 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 | None | None |
name | str | 'select-ntt-implementations' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...SlotExtent
data View source
SlotExtent = int | Literal['full']Specialization
class View source
Specialization(backend: OperationBackend, executable: ProgramExecutable)Pair an input-specialized computation with its linked executable.
source records the computation before specialization. compilation contains the transformed Program and pass reports; backend and executable provide its linked execution. The executable retains its prepared bindings. Replacing a Program or binding requires preparing and linking a new specialization.
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.
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.
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. Equal keys under one theme 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 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.
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: ...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.
Python functions, bound methods and callable objects share source capture. Bound object members are read lazily; writes to those objects are rejected. 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. Engine codec preparation calls become 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 and in-place Tensor operations 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, resources: CkksDeviceResources | RnsContext | NttContext | Iterable[CkksDeviceResources | RnsContext | NttContext]=(), keys: Mapping[object, object] | Iterable[object] | EvaluationKeySet=(), 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 CompiledCallable directly or as a decorator.
compile(source, **options) returns a callable for a Python callable, Program, or Compilation. For Python sources, @compile uses default options and @compile(**options) configures the decorator. Options are passed to CompiledCallable construction.
default_lower_and_fuse_pipeline
function View source
def default_lower_and_fuse_pipeline(backend: OperationBackend | None=None) -> Pipeline: ...Build an editable lowering-and-fusion pipeline for a mixed-level Program.
The recipe lowers high-level encrypted arithmetic, propagates represented entry state, removes dead values, hoists compatible rotations, reuses internal pure computations, and selects supported fusion regions. Supplied CKKS transitions are preserved. Rescale and relinearization scheduling require caller-added passes before depth and scale assignment.
The selected registry is shared through CompileWorkspace. Lowering and implementation selection complete their operation material declarations using that registry and the workspace's optional key_layouts mapping. Passes read available Tensor facts from the Compilation's material bindings.
Lowerings are selected per operation from registered implementations and their fusion support. Selection uses represented operation and layout facts. Missing preparation facts may remain in the optimized Program until linking requires them.
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.
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 missing Tensor bindings from supplied data providers and keys.
Key entries named by a symbol or its label are direct assignments and bypass metadata selection. Otherwise, descriptions select a single candidate using CKKS operand rows, placement, and compatible execution groups. Absent, ambiguous, or conflicting matches remain unresolved. Existing bindings are preserved. The returned symbols identify entries still requiring data; key generation is a separate provisioning operation.
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.