fhelium.compile.mlir
MLIR compiler for FHElium CKKS programs.
The fhelium_ckks dialect types record each value's depth, actual scale, polynomial domain, residue representation and component count; operations infer result state natively. capture records Eager Engine calls and the public Tensor work they consume as a fhelium_ckks function, Pipeline runs native and Python-defined passes, execute runs a function through the Engine, Preparation runs its outlined ciphertext-independent part, and MaterialGuard decides whether a later call can reuse the compiled function with rebound materials.
This package requires the compiler extension in fhelium._mlir, built from csrc/compiler.
CapturedFunction
class View source
CapturedFunction(context: ir.Context, module: ir.Module, config: CkksConfig, materials: dict[str, object], outputs: Any, name: str = 'entry', statistics: dict[str, float] = field(default_factory=dict), arguments: tuple[int, ...] = (), sources: dict[str, Path] = field(default_factory=dict))An MLIR module holding one captured function and its material bindings.
materials maps each fhelium_ckks.material symbol to the bound object. outputs reproduces the returned Python structure, with integers indexing the function results. arguments lists the call argument positions of the function arguments. sources maps the symbols of materials found in the call arguments to their paths.
Attributes
| Name | Type | Default/value |
|---|---|---|
context | ir.Context | |
module | ir.Module | |
config | CkksConfig | |
materials | dict[str, object] | |
outputs | Any | |
name | str | 'entry' |
statistics | dict[str, float] | field(default_factory=dict) |
arguments | tuple[int, ...] | () |
sources | dict[str, Path] | field(default_factory=dict) |
function
property
function: func.FuncOpfunction_named
method
def function_named(name: str) -> func.FuncOp: ...preparation
property
preparation: func.FuncOp | NoneThe preparation function that outlining assigned to the function.
callees
property
callees: list[func.FuncOp]Private functions that the entry reaches through fhelium_ckks.bootstrap or func.call, in first-use order.
to_text
method
def to_text() -> str: ...DiskCache
class View source
DiskCache(directory: str | os.PathLike[str])Trace entries and source aliases under directory.
resolve
method
def resolve(source: str) -> str | None: ...The trace key that source key source names, if stored.
alias
method
def alias(source: str, trace: str) -> None: ...load
method
def load(key: str, device: torch.device, *, graphs: str | bool) -> Entry | None: ...store
method
def store(key: str, function: Any, *, device: torch.device, program: bytes, recipes: Sequence[tuple[str, object, int]], states: Sequence[ValueState], structure: Any, locations: Mapping[str, tuple[str, Sequence[tuple]]] | None) -> None: ...Write the entry of function, a planned schedule function whose Ciphertext payloads lie on device; a schedule the artifact format does not accept is not stored.
Specialization
class View source
Specialization(function: Any, constants: tuple[object, ...], recipes: tuple[tuple[str, object, int], ...], materials: dict[str, Any], preparation: Preparation | None, guard: MaterialGuard, results: _Results, path: str, positions: tuple[int, ...], timings: dict[str, float])One compiled call signature.
function is the schedule function that runs; it reads the payloads of the Ciphertext arguments at positions followed by constants, which recipes derive from the Backend resources and materials. path records how it was obtained: "compiled", "trace" (disk entry found by trace key) or "source" (disk entry found by source key, without capture). guard checks that a call reaches the bound materials and compiled holds the captured and linked function when the call compiled it. timings holds the host seconds of its stages; calls, rebinds and refreshes count executions, material rebindings and preparation reruns.
update
method
def update(engine: Engine, changed: Mapping[str, object]={}, *, force: bool=False) -> None: ...Bind the replaced materials changed and rerun preparation when it reads a replaced or modified material, or with force.
Prepared results of the previous layouts are written into the storage of the bound prepared materials, so the schedule reads them at unchanged addresses; prepared materials that share storage with input materials are rebound instead.
run
method
def run(arguments: Sequence[object]) -> Any: ...compile_function
function View source
def compile_function(function: Callable[..., object], engine: Engine, arguments: Sequence[object], *, pipeline: Pipeline | None=None, schedule: bool=False, lowering: Pipeline | None=None, registry: Any=None, names: Mapping[int, str] | None=None, placement: Placement='managed') -> tuple[CompiledFunction, Any]: ...Compile function for arguments and return it with the outputs of its first execution.
pipeline replaces the CKKS pipeline that precedes preparation outlining (default_pipeline with placement) and lowering the pipeline that follows it on the entry and its callees (default_lowering of arguments). With schedule, the linked program is also instantiated as one exec function and translated to a Runner schedule. registry selects the operation implementations (the Engine Backend's by default) and names gives material symbols by object id.
MaterialGuard
class View source
MaterialGuard(captured: CapturedFunction, function: Callable[..., object] | None=None, engine: Engine | None=None, device: torch.device | None=None)Check that a call reaches materials of the bound layouts.
Materials in captured.sources are read from the call arguments; other materials are located from function or, for evaluation keys that engine selected from engine.keys, as the key it selects for the same role, rotation step and depth on device. Materials that are not located stay bound as captured. A declared key matches keys of its layout on device, the execution device.
at
method
def at(locations: Mapping[str, tuple[str, list[tuple]]], materials: Mapping[str, object], function: Callable[..., object] | None, engine: Engine | None, device: torch.device | None=None) -> MaterialGuard: ...A guard of materials at known locations (symbol to root and path), as locations reports them.
locations
property
locations: dict[str, tuple[str, list[tuple]]]The root ("arguments", "function" or "engine") and path of each located material.
resolve
method
def resolve(arguments: Sequence[object]) -> dict[str, object]: ...The materials at the guarded locations for a call with arguments.
located
property
located: intcheck
method
def check(arguments: Sequence[object]) -> dict[str, object] | None: ...Return the replaced materials by symbol, or None when a located material changed layout.
An empty result means the call reaches every bound material.
Pipeline
class View source
Pipeline(passes: tuple[str | PythonPass, ...], verify: bool = True)Run passes in order within one MLIR PassManager.
A string entry is a textual pipeline element anchored at builtin.module, for example "func.func(cse)". A callable entry run(op, pass_), a function or an object with __call__, is a Python-defined pass on the module; it may call pass_.signal_pass_failure(). Python passes must not keep operation handles after they return, since later native passes may erase those operations.
Attributes
| Name | Type | Default/value |
|---|---|---|
passes | tuple[str | PythonPass, ...] | |
verify | bool | True |
numerics
method
def numerics() -> tuple[tuple[str | PythonPass, bool | None], ...]: ...Each entry with changes_numerics of it.
run
method
def run(captured: CapturedFunction, *, timing: bool=False) -> CapturedFunction: ...Preparation
class View source
Preparation(captured: CapturedFunction, function)The preparation function of an outlined captured function.
symbols names the materials that bind its results in order; inputs the materials it reads.
of
method
def of(captured: CapturedFunction) -> Preparation | None: ...bound
method
def bound(materials: Mapping[str, object]) -> bool: ...run
method
def run(engine: Engine, materials: Mapping[str, object], *, check_types: bool=False) -> dict[str, object]: ...Return the prepared materials computed from materials.
Plaintext encoding rounds from the Engine's random stream, in the order of the captured calls.
rebind
method
def rebind(engine: Engine, materials: dict[str, object], changed: Mapping[str, object]) -> dict[str, object]: ...Update materials with changed and rerun preparation when it reads them.
StateMismatch
class View source
StateMismatch()Bases: AssertionError
TracedValue
class View source
TracedValue(trace: _Trace, value: ir.Value, device: torch.device | None=None)A ciphertext or plaintext SSA value during capture.
Attributes
| Name | Type | Default/value |
|---|---|---|
assert_state | Ciphertext.assert_state |
depth
property
depth: intscale
method
def scale(scale: float) -> None: ...polynomial_domain
property
polynomial_domain: strresidue_representation
property
residue_representation: strrepresentation
property
representation: str | Nonecomponent_count
property
component_count: intmodulus_basis
property
modulus_basis: strbatch_shape
property
batch_shape: torch.Sizebatch_size
property
batch_size: intis_batched
property
is_batched: boolcompression_layout
property
compression_layout: str | Noneunique_count
property
unique_count: intring_dimension
property
ring_dimension: intprime_ids
property
prime_ids: tuple[int, ...]limb_count
property
limb_count: intis_ntt_domain
property
is_ntt_domain: boolis_coefficient_domain
property
is_coefficient_domain: boolis_rns
property
is_rns: boolis_integer_coefficients
property
is_integer_coefficients: boolis_slots
property
is_slots: booldevice
property
device: torch.deviceroll
method
def roll(shifts: int, dims: int | None=None) -> TracedValue: ...sum
method
def sum(dim: int | None=None, keepdim: bool=True) -> TracedValue: ...to
method
def to(device: torch.device | str, *, non_blocking: bool=False, copy: bool=False) -> TracedValue: ...Record fhelium_memory.transfer of the payload to device.
cpu
method
def cpu(*, copy: bool=False) -> TracedValue: ...pin_memory
method
def pin_memory(*, copy: bool=False) -> TracedValue: ...clone
method
def clone() -> TracedValue: ...select_batch
method
def select_batch(index: int, *, dim: int=0) -> TracedValue: ...stack_batch
method
def stack_batch(values: Sequence[TracedValue]) -> TracedValue: ...unbind_batch
method
def unbind_batch(*, dim: int=0) -> tuple[TracedValue, ...]: ...ValueState
class View source
ValueState()Bases: NamedTuple
State recorded in a fhelium_ckks ciphertext or plaintext type.
kind is "ciphertext", "plaintext", "compressed_plaintext" or None for other types. Depth -1 and scale 0 denote an unassigned depth and scale. compression_layout and unique_count describe compressed plaintexts.
Attributes
| Name | Type | Default/value |
|---|---|---|
kind | str | None | |
depth | int | |
scale | float | |
polynomial_domain | str | |
residue_representation | str | |
representation | str | None | |
component_count | int | |
modulus_basis | str | |
batch_shape | tuple[int, ...] | |
compression_layout | str | None | |
unique_count | int |
capture
function View source
def capture(function: Callable[..., object], engine: Engine, arguments: Sequence[object], *, context: ir.Context | None=None, name: str='entry', names: Mapping[int, str] | None=None) -> CapturedFunction: ...Call function(*arguments) once and record its Engine calls.
Ciphertext arguments become function arguments typed by their current state; other arguments are passed unchanged, and the values that the function consumes from them become located materials. names maps id(material) to the symbol that material receives instead of a generated one.
chain_attribute
function View source
def chain_attribute(context: ir.Context, config: CkksConfig) -> ir.Attribute: ...Return #fhelium_ckks.chain for config.
The attribute records the Q and P primes, the Q basis of every depth, default scales, the binary64 rescale ratios
ciphertext_type
function View source
def ciphertext_type(chain: ir.Attribute, *, depth: int, scale: float, polynomial_domain: str='coefficient', residue_representation: str='standard', component_count: int=2, modulus_basis: str='Q', batch_shape: Sequence[int]=()) -> ir.Type: ...compressed_plaintext_type
function View source
def compressed_plaintext_type(chain: ir.Attribute, *, depth: int, scale: float, polynomial_domain: str, residue_representation: str, compression_layout: str, unique_count: int, modulus_basis: str='Q', batch_shape: Sequence[int]=()) -> ir.Type: ...create_context
function View source
def create_context() -> ir.Context: ...Create an MLIR context with the FHElium dialects loaded and passes registered.
default_pipeline
function View source
def default_pipeline(*, entry_depth: int | None=None, placement: Placement='managed') -> Pipeline: ...The CKKS pipeline that precedes preparation outlining.
In order: fhelium-assign-ckks-depths gives arguments of unassigned depth entry_depth and aligns written joins, fhelium-assign-ckks-scales assigns actual scales, canonicalize folds identities that keep every residue and removes unused operations, fhelium-factor-rotations rotates sums of equally rotated managed values once, fhelium-place-ckks-management places relinearization, rescaling and alignment of managed values by the lazy rule, fhelium-lower-logical-to-ckks lowers fhelium_logical operations one to one, fhelium-sink-mod-switch moves row selections toward their producers, and canonicalize and cse clean up. placement="all" also lets the factoring and placement passes rewrite written fhelium_ckks rotations, relinearizations and rescales. Pipeline.numerics reports which passes can change ciphertext residues.
execute
function View source
def execute(captured: CapturedFunction, engine: Engine, arguments: Sequence[object], *, check_types: bool=False, materials: Mapping[str, object] | None=None) -> Any: ...Run the captured function on its ciphertext arguments in argument order.
materials defaults to the captured bindings. When outlining gave the function a preparation function and materials lacks its outputs, the preparation function runs first.
key_type
function View source
def key_type(context: ir.Context, role: str, prime_ids: Sequence[int]=(), digit_prime_ids: Sequence[Sequence[int]]=()) -> ir.Type: ...Return !fhelium_ckks.key with the key's row and digit layout.
plaintext_type
function View source
def plaintext_type(chain: ir.Attribute, *, depth: int, scale: float, representation: str, polynomial_domain: str='coefficient', residue_representation: str='standard', modulus_basis: str='Q', batch_shape: Sequence[int]=()) -> ir.Type: ...required_keys
function View source
def required_keys(captured: CapturedFunction) -> dict[str, object]: ...The evaluation keys the operations of captured's module use, from the IR alone.
"relinearization" and "conjugation" are booleans, "rotation_steps" lists the rotation steps normalized to "other_roles" the roles of other key operands, such as the switching keys of bootstrapping. Logical products and rotations count before they are lowered; a sum needs the steps
value_state
function View source
def value_state(type_: ir.Type) -> ValueState: ...Read the value state of an MLIR type in one native call.