fhelium.compile.passes
Built-in partial transforms for captured tensor and CKKS operations.
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: ...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: ...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: ...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: ...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: ...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.
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: ...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.
LowerSpecializedCollectivesPass
class View source
LowerSpecializedCollectivesPass(lower_ciphertext_add: bool = True, name: str = 'lower-specialized-collectives')Replace selected specialized collectives with generic region forms.
The pass exposes local combine arithmetic without proving associativity, rank uniformity, cross-rank ordering, or deadlock freedom. Callers remain free to preserve specialized operations for whole-operation providers.
Attributes
| Name | Type | Default/value |
|---|---|---|
lower_ciphertext_add | bool | True |
name | str | 'lower-specialized-collectives' |
run
method
def run(compilation: 'Compilation') -> PassResult: ...Expose CKKS add as the combine region of ciphertext all-reduce.
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: ...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: ...SvgGraphDirection
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.
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.
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.