Dialects, capture, and passes
FHElium's compiler is an MLIR project in csrc/compiler: TableGen definitions of its dialects and passes, their C++ implementations, a C API, and Python extensions that the build installs as the package fhelium._mlir, which also contains the upstream MLIR Python bindings. fhelium.compile.mlir captures Eager functions as fhelium_ckks functions in this IR and runs pipelines of native and Python passes on them. This article describes the dialect definitions, the capture mechanism, the reference interpreter, and the pass protocol; Lowering, linking, and the Runner continues from the pipelined function.
Source layout
| Path | Content |
|---|---|
csrc/compiler/include/fhelium-compiler/ | TableGen definitions and C++ headers. Dialect/<Name>/IR/ defines each dialect, fhelium_ckks (CKKS), fhelium_logical (Logical), fhelium_rns (RNS), fhelium_ntt (NTT), fhelium_dist (Dist), fhelium_memory (Memory), and exec (Exec), with its operations in <Name>Ops.td; Dialect/<Name>/Transforms/Passes.td defines the passes over that dialect, Conversion/Passes.td the lowerings between dialects, Analysis/ the key-requirement and link-plan analyses, and Schedule/ the exec schedules |
csrc/compiler/include/fhelium-compiler-c/ | C API: dialect registration and CKKS type constructors (Dialect/), pass registration (Passes.h), and analyses (Analysis.h) |
csrc/compiler/lib/ | Implementations in the same layout: dialects with type inference, verifiers, and folders (Dialect/<Name>/IR/), one file per pass (Dialect/<Name>/Transforms/), rewriting helpers of the passes that create CKKS operations (Dialect/CKKS/Utils/), lowerings (Conversion/LogicalToCKKS/, Conversion/CKKSToRNS/), analyses (Analysis/), schedule translation and planning (Schedule/), and the C API (CAPI/) |
csrc/compiler/python/ | Python extensions: CKKS types, compiler passes, the Backend link plan, and schedules |
fhelium/compile/mlir/ | Capture, interpreter, pipelines, preparation, linking, and the compile cache |
fhelium/ir/ | The operation catalog (_operations.py) and the CKKS state equations (ckks_state.py) shared with Eager and the Backend |
The compiler is configured against an MLIR installation with the CMake option FHELIUM_MLIR_DIR or MLIR_DIR. Operation builders generated from the TableGen definitions are available in Python as the modules fhelium._mlir.dialects.fhelium_ckks, fhelium_logical, fhelium_rns, fhelium_ntt, fhelium_dist, fhelium_memory, and exec.
Types and type inference
fhelium_ckks types carry value state. !fhelium_ckks.ciphertext<depth, scale, domain, residues, components> records the consumed-depth index, the actual scale as a binary64 value, the polynomial domain, the residue representation, the component count, and, when they differ from the defaults, the modulus basis and the batch shape; plaintext and compressed-plaintext types record the corresponding state, and !fhelium_ckks.key<role, prime_ids, digit_offsets, digit_ids> records a key's role, stored rows, and digit partition. Each type also carries the modulus chain #fhelium_ckks.chain, which the function attribute fhelium_ckks.chain holds as well: the Q and P primes, whose positions are the prime ids, the Q basis of each depth, the default scale and the binary64 rescale ratio (\rho_d) of each depth, the ring dimension, and the Galois generator.
Most fhelium_ckks operations derive from CKKS_InferOp and infer their result types natively from their operand types and the chain, with the same equations as fhelium/ir/ckks_state.py and Eager: a product multiplies actual scales, a rescale from depth (d) divides by the chain's ratio (\rho_d), and a depth transition drops the primes of one depth group. A builder therefore takes operands and attributes only; ck.MultiplyIntegerScalarOp(value, scalar=2) creates a result with the operand's state.
fhelium.ir._operations.OPERATIONS catalogs every operation that Eager dispatches or the Backend registry resolves by its MLIR name, with its effect and, for RNS and NTT operations, the residue structure that fusion and code generation read. The MLIR name is the operation identity across capture, the registry, Eager dispatch, and generated kernels.
Capture
fhelium.compile.mlir.capture(function, engine, args) creates a module with one function @entry and calls the Python function once. Ciphertext arguments become TracedValue objects whose state properties read their MLIR types. While capture runs, the Engine's capture hook (Engine.capture_hook) routes the Engine's value operations on the capturing thread to the handlers in _capture.py:_HANDLERS, which append operations instead of executing. An Engine operation without a handler runs its Eager definition on the traced values, which records the operations it calls; compositions such as linear transforms and polynomial evaluation are captured this way. Bootstrap calls are captured as calls of one private callee per prepared plan and input type.
Untraced values that a recorded operation consumes become fhelium_ckks.material operations (Materials and preparation functions). ATen calls on public Tensors execute during capture and are recorded as fhelium_ckks.tensor_call operations when an Engine operation consumes their results. Constants that algorithms store into their caches during capture stay in a capture-local overlay, so Eager caches never receive traced values. .to(device), .cpu(), and .pin_memory() on traced values record fhelium_memory.transfer, and ciphertext collectives record fhelium_dist.all_reduce_add_ciphertext with the process group as a material.
Python control flow runs at capture time: loops unroll, and a branch takes the path that the traced state or static arguments select. The function's outputs must be traced values in tuples or lists; CapturedFunction.outputs records their structure.
Reference semantics
fhelium.compile.mlir.execute(captured, engine, args, check_types=False, materials=None) (_interpret.py) interprets a fhelium_ckks function by calling, for every operation, the Engine method it was captured from, and for tensor_call its ATen operator. With check_types, each result's Eager state is compared with its MLIR type. The interpreter defines the semantics of the dialect: a compiled function decrypts to the result of interpreting its pipelined module, and with the same rounding order to the same residues. The preparation function of a specialization runs through the same interpreter.
Pass pipelines
Pipeline(passes, verify=True) (_pipeline.py) adds its entries in order to one PassManager anchored at builtin.module. A string entry is a textual pipeline element such as "func.func(cse)" or "fhelium-outline-preparation"; a callable entry is a Python pass called as run(module_op, pass_), which may call pass_.signal_pass_failure(). With verify, the module is verified after each pass, and run(captured, timing=True) enables MLIR pass timing. A Python pass must not keep operation handles after it returns, because later native passes may erase those operations.
default_pipeline(*, entry_depth=None, placement="managed") contains, with the native sources relative to csrc/compiler/lib/ and the column Residues from CHANGES_NUMERICS in _pipeline.py:
| Pass | Source | Residues | Effect |
|---|---|---|---|
fhelium-assign-ckks-depths | Dialect/CKKS/Transforms/AssignCkksDepths.cpp | kept | Gives unassigned arguments entry-depth, aligns additive joins of different depths with mod_switch, places unplaced encodings at the depth of their consumer, and infers result types again |
fhelium-assign-ckks-scales | Dialect/CKKS/Transforms/AssignCkksScales.cpp | kept | Assigns scales to values whose scale is 0 and rejects additive joins of different assigned scales |
canonicalize | folders in Dialect/CKKS/IR/CKKSDialect.cpp, Dialect/Logical/IR/LogicalDialect.cpp | kept | Folds mod_switch and reinterpret_scale; removes unused operations without random-stream effects |
fhelium-factor-rotations | Dialect/Logical/Transforms/FactorRotations.cpp | changed | explicit=true (placement="all") also on fhelium_ckks.rotate |
fhelium-place-ckks-management | Dialect/Logical/Transforms/PlaceCkksManagement.cpp | kept; changed with explicit=true | Inserts relinearization, rescale and alignment for logical operations by the lazy rule and sets each logical result to its pending state; with explicit=true it also defers written relinearizations and rescales |
fhelium-lower-logical-to-ckks | Conversion/LogicalToCKKS/LogicalToCKKS.cpp | kept | Lowers each placed logical operation one to one; materials relinearization_key and rotation_key_<step> with normalized steps |
fhelium-sink-mod-switch | Dialect/CKKS/Transforms/SinkModSwitch.cpp | kept | Moves row-dropping mod_switch above single-use additions, subtractions, negations and integer products |
canonicalize, cse | upstream | kept | Fold and merge the lowered operations |
Placement keeps a map from each managed SSA value to its current value and pending rescale: a later operation that applies a pending step updates the entry, so one relinearization or rescale serves all later users, as the in-place materialization of Eager does. Values not produced by a logical operation are brought to two-component coefficient form before logical arithmetic without being updated. Alignment (logical::planAlignment, LogicalDialect.cpp) aligns the operands of a ciphertext multiply by depth only, with one mod_switch of the lower-depth operand, and the operands of add and subtract by depth and scale; the logical result types of both follow the same plan. For additive joins, alignment and the multiplier ckks::transitionMultiplier (CKKSDialect.cpp) compute the integer factor from the binary64 rescale ratios with rational arithmetic and ties to even, as fhelium/eager/_operators.py:align does. ckks.encode, prepare_compressed, add_scalar and multiply_scalar, and logical operations with Tensor or real scalar operands, carry read and write effects on the resource fhelium.random_stream, so CSE and DCE keep each draw of the stochastic rounding stream. fhelium.compile.mlir.required_keys(captured) returns the relinearization, conjugation, rotation-step and other key roles that the module's logical and CKKS operations use, from the native walk requiredKeys (Analysis/KeyRequirements.cpp) exposed as fhelium_ckks.required_keys.
Captured Eager functions already carry assigned state, so the assignment passes change them only where the source left state open, and placement changes only logical operations unless placement="all". After the caller's pipeline, fc.compile runs fhelium-outline-preparation (compile/mlir/_compile.py:_run_pipeline), which moves the ciphertext-independent slice of each public function into its preparation function, and then the lowering stage on the entry and its callees without the preparation function (_lower): default_lowering(arguments), which contains fhelium-hoist-rotations, fhelium-lower-ckks-to-rns{key-switches=true}, cse, and, when a registered fusion implementation covers the device type of the Ciphertext arguments, fhelium-fuse-rns, or the lowering pipeline of the callable for the call signature.
Extending the compiler
An operation is added to its dialect's TableGen file with its equations in the description and, for CKKS operations, its type inference; its catalog entry in fhelium/ir/_operations.py, its Eager definition, its capture handler when Eager dispatch alone does not record it, and its Backend implementation complete it. A native pass is defined in the Passes.td of the dialect it transforms, or in Conversion/Passes.td when it lowers one dialect to another, implemented in the corresponding directory of csrc/compiler/lib/, and registered in lib/CAPI/Transforms/Passes.cpp; a Python pass is placed in a Pipeline. Passes and implementations execute with the authority of the process; loading an extension establishes no isolation.