Compile pipeline
Compile turns a Python function over Eager CKKS values into a linked Backend schedule. fhelium.compile.compile wraps the function as a compiled callable, and each call with a new call signature produces a specialization: the function captured as an MLIR module, transformed by a pass pipeline, lowered to residue-level operations, linked against Backend implementations, and planned as a Runner schedule. Later calls with the same signature run the schedule directly. This page defines the stages, the reuse rules of a specialization, and the persistent forms of a compiled function.
Stages
| Stage | Product | Specialization.timings key |
|---|---|---|
| Capture | fhelium_ckks module of the Engine operations the call applies and the Torch work they consume | capture |
| Caller pipeline and outlining | Transformed module with a preparation function | pipeline |
| Preparation | Prepared materials computed by the preparation function | prepare |
| Lowering stage | fhelium_rns/fhelium_ntt function with generated-kernel regions | lower |
| Link | Backend fragments for each operation with compiled kernels, and the first execution of the planned schedule on the call's arguments | link |
| Schedule | One exec function translated to a Runner schedule, with CUDA Graph segments on CUDA | schedule |
| Material guard | Locations of the materials for later calls | guard |
With the persistent cache enabled, identity records the source identification, cache_load the lookup, and store the write of a new entry. A specialization loaded from the cache records constants for building its table Tensors, first for its first execution, and locate for binding materials at stored locations.
Capture
Capture calls the source function once. Each Ciphertext argument is replaced by a traced value whose depth, scale, domain, residue representation, component count, modulus basis, and batch shape are read from its MLIR type. While the function runs, the Engine routes its value operations on the capturing thread to capture handlers, which append fhelium_ckks operations instead of executing them; other threads and other Engines are unaffected. An Engine method without a handler runs its Eager definition on the traced values, which records the handled operations it calls; a definition that reads a traced value's residues cannot be captured. A PyTorch operator applied to public Tensors runs during capture and is recorded as fhelium_ckks.tensor_call when an Engine operation consumes its result.
Python control flow, Python scalars, and attribute reads execute during capture, so the module contains the operations of the path the call took, with Python scalar values as constants. A compiled callable called inside another compiled function runs its source function, so its operations become part of the enclosing module. A compiled function takes at least one Ciphertext argument and returns traced ciphertexts or plaintexts, alone or nested in tuples and lists.
Values that an operation reads without receiving them as Ciphertext arguments become materials: evaluation keys, public Tensors, fixed ciphertexts and plaintexts, and process groups. Capture preserves the key and Tensor dataflow of the source; it neither generates keys nor selects keys by role. The Compiler IR page defines the operations and types.
Caller pipeline
A pipeline is an ordered sequence of passes run in one MLIR PassManager on the captured module. An entry is either a textual pass-pipeline element anchored at builtin.module, such as "func.func(cse)", or a Python callable run(op, pass_) that rewrites the module through the MLIR Python bindings. The default pipeline is:
| Pass | Effect |
|---|---|
func.func(fhelium-assign-ckks-depths) | Assigns the option entry-depth, set by default_pipeline(entry_depth=...), to arguments of unassigned depth, inserts mod_switch on the lower-depth operand of an addition or subtraction whose operand depths differ, and places unplaced encodes at the depth of the ciphertext they multiply |
func.func(fhelium-assign-ckks-scales) | Assigns actual scales to values without one: ciphertext arguments receive the option entry-scale or the chain's default scale at their depth, and encoded plaintexts take the scale of the ciphertext they are added to; an addition of two different assigned scales is an error |
func.func(canonicalize) | Folds identities that keep every residue, such as |
func.func(fhelium-factor-rotations) | Rewrites fhelium_logical operands, which saves one rotation; with explicit=true also for fhelium_ckks.rotate and removes rotations by multiples of the slot count. The result decrypts to the same slots with different noise |
func.func(fhelium-place-ckks-management) | Places relinearization, rescaling and alignment for the fhelium_logical operations by the lazy rule: a product keeps its rescale, and a ciphertext product also its relinearization, pending; the next product or Tensor or scalar operand applies the pending steps first, a rotation or sum applies only a pending relinearization, an addition of operands in equal states keeps their pending state, and a function result or a written CKKS operation applies every pending step. Operands of a ciphertext product at different depths are aligned by mod-switching the operand with more remaining capacity to the other operand's depth; their scales stay as they are, and the product has the scale explicit=true, relinearizations and rescales written as fhelium_ckks operations are deferred in the same way |
func.func(fhelium-lower-logical-to-ckks) | Lowers each placed fhelium_logical operation to the CKKS operation its operands' states select: products of ciphertexts become NTT conversion and multiply, a product with a public Tensor encodes the Tensor at the operand's depth and default scale and multiplies in the NTT domain, a product with an integer becomes multiply_integer_scalar, a product with a real scalar multiply_scalar, roll by rotate with the material rotation_key_<s> for sum the relinearization_key |
func.func(fhelium-sink-mod-switch) | Moves a mod_switch that only drops rows above single-use additions, subtractions, negations and integer products, so that they run on fewer rows with equal residues |
func.func(canonicalize), func.func(cse) | Fold the lowered operations and eliminate common subexpressions |
Each pass re-infers result types in program order, so the function signature follows the returned values. Assigned depths and actual scales are kept; the assignment passes fill only unassigned state. Operations that draw from the Engine's random stream, namely encodes, scalar additions, real scalar products and the logical operations that lower to them, are neither merged nor removed and keep their order. Every pass except fhelium-factor-rotations keeps the residues of the program executed as written, with fhelium_logical operations following the lazy rule of Eager ciphertext operators, so the compiled function reproduces Eager residues for programs without equally rotated sums. default_pipeline(placement="all") sets explicit=true on factoring and placement, which then also rewrite written CKKS rotations, relinearizations and rescales; the default placement="managed" leaves written CKKS operations as the source applies them. Pipeline.numerics() lists for each entry whether it can change residues.
Any upstream MLIR pass registered in the compiler, such as canonicalize, is available by its textual name. A Python pass may call pass_.signal_pass_failure() and must not retain operation handles after it returns, since later native passes may erase those operations. Pipeline(passes, verify=True) verifies the module after every pass, and Pipeline.run(captured, timing=True) reports MLIR pass timing. After the caller pipeline, compilation runs fhelium-outline-preparation, which moves the ciphertext-independent slice into the preparation function.
Lowering stage
The lowering stage runs on the entry and its bootstrap callees after preparation outlining; the preparation function stays at the CKKS level. The lowering option replaces the stage with a Pipeline or a function from the call signature to a Pipeline. The default stage, default_lowering(signature), contains three Backend passes and common-subexpression elimination between lowering and fusion:
| Pass | Effect |
|---|---|
fhelium-hoist-rotations | Groups nonzero rotations of one coefficient-domain ciphertext whose keys share a layout into rotate_many operations that share one key-switch decomposition. The group size follows a ring-row traffic model and is bounded so that the live ciphertexts, with each group's ModUp and accumulator workspace, fit within the option memory-limit, which the default stage sets to 90% of the CUDA device memory that is free or cached by the allocator when the Ciphertext arguments lie on one CUDA device. |
fhelium-lower-ckks-to-rns | Replaces CKKS arithmetic, NTT transitions, residue conversion, rescale, and modulus switching with fhelium_rns and fhelium_ntt operations reading fhelium_rns.table values. Rotations of coefficient ciphertexts and relinearizations with rescale become hybrid key switches over the key's digits when the key layout is declared; other key switches remain whole operations. With key-switches=false, every key switch remains a whole operation. |
cse | Merges equal RNS and NTT operations and tables that lowering produced for different CKKS operations. |
fhelium-fuse-rns | Groups RNS and NTT operations on one prime basis, between key switches, into fhelium_rns.fused regions executed by generated Triton kernels. NTT transforms are region anchors, at most eight per region. The default stage contains this pass only when the Backend registry holds a fusion implementation for the device of the Ciphertext arguments; the built-in Triton implementation fuses CUDA Tensors. |
A lowering stage without fhelium-fuse-rns links each RNS and NTT operation separately, and one without fhelium-hoist-rotations keeps rotations separate; passes placed between lowering and fusion transform the RNS/NTT function. The caller pipeline determines the CKKS module that the stage receives.
Linking and scheduling
Linking groups the lowered operations by their name, attributes, and operand and result types, and lowers one Backend fragment per group through the implementation registry, which identifies each operation by its MLIR name. Table descriptions are resolved to Tensors built from the Engine's device resources, and materials are bound by symbol. Each fragment is traced on placeholders with the layouts of its operands; only operator calls whose inputs are all link-time constants execute while lowering. Scheduling composes the fragments into one exec function and translates it to a Runner schedule. The Triton kernels that the fragments launch compile concurrently, and the planned schedule then runs once on the call's arguments; that run returns the outputs of the first call. On CUDA, later calls run the schedule through CUDA Graphs of its capture-safe segments according to the graph option. Compiled execution defines schedules, storage classes, and Graph segments.
The registry is that of the Engine's Backend for the arguments' device unless backend= supplies an OperationBackend.
Call signatures and specializations
A call signature describes the leaves of a call's arguments, with tuples, lists, and dictionaries flattened: the type of each leaf, the shape, strides, dtype, device, and gradient requirement of each Tensor, the CKKS state of each ciphertext, plaintext, and key, and the value of each Python scalar; it also records the argument structure and the Torch grad, inference, and autocast modes. Tensor contents and storage addresses are excluded. A call whose signature matches a resident specialization runs that specialization; another signature prepares a new one, or raises SpecializationMiss when the callable was created with on_miss="error".
Material location and rebinding
After compiling a specialization, its material guard locates every material again, so that a later call can tell whether it still reads the same objects:
- a material reached from the call arguments is located by its path in the arguments;
- an evaluation key installed in the Engine is located in the Engine's key inventory;
- other materials are found by a bounded breadth-first scan from the source function through bound instances (
self), closure cells, defaults, the globals the code reads, containers, and object attributes.
On each call, the guard resolves the located paths. An object of the bound layout that replaced the bound one is rebound, and a material of another layout prepares a new specialization. The preparation function reruns when a material it reads was rebound or when a Tensor it reads was modified in place, as PyTorch version counters report; refresh_materials reruns it for changes that version counters do not record. A prepared result that keeps its layout is written into the storage of the previous prepared material, so the schedule reads it at an unchanged address. A material that the scan does not locate stays bound as captured and appears in stats()["specializations"][i]["unlocated"].
Compile locates the Engine the same way: engine=None selects the one Engine among the arguments and the objects reachable from the source, and engine= selects one when there are several. Keys and tables need no compile option, because the function's dataflow names the keys it uses and the Backend builds the tables.
Persistent cache
With cache=True, specializations persist in $FHELIUM_CACHE_DIR/mlir, or ~/.cache/fhelium/mlir when the variable is unset. An entry is an FHElium artifact holding the planned schedule, with Graph segments for a graphed function, the kernel images and fragment constants it reads, the recipes of its table arguments, the result value states and output structure, and the material locations; the MLIR bytecode of the pipelined module is stored beside it. Material Tensor contents are excluded.
Two keys find an entry:
| Key | Digest | A hit skips |
|---|---|---|
| Trace key | Bytecode of the captured module, the layouts of the ciphertext payloads and bound materials, the compile options, including the textual passes and the source identities of the Python passes of the caller pipeline and the lowering stage, and the environment (Python sources, compiler and native libraries, Triton) | The caller pipeline, lowering, fusion, linking, and planning; capture and the preparation function still run |
| Source key | The Python source and the static values it reads, with the call signature | Capture as well; materials are located at the stored locations and the stored module's preparation function computes the prepared materials |
A source key exists when the source lies in the statically checked subset of Python that the source scan accepts and every material is located from the call arguments, the function, or the Engine. The source key names a file holding the trace key of the entry compiled for it. stats()["cache"] gives the reason when a source is not identified before capture. A Python pass whose source the scan does not identify, or an implementation registry other than FHElium's, makes the call ineligible for the disk cache. The default lowering stage is keyed as the default regardless of its derived memory-limit, while a custom stage is keyed by its passes and options. Persistent entries outlive clear().
Exported artifacts
fhelium.compile.export writes the specializations of chosen example calls to one artifact, and fhelium.compile.load or the C++ fhelium::Artifact loader runs them without capture or linking. Keys are recorded by role and layout and bound by the loading process, so the exported function may read keys declared without key data; NTT, RNS, and key-switching tables are rebuilt by recorded builder calls; prepared plaintexts and other materials of the function are embedded; materials located in the call arguments are bound from each call, and a preparation function that reads them becomes a per-call preparation entry. Persistence and artifacts defines the artifact contents.
Numerical agreement with Eager
A compiled function computes the same residues as Eager execution of its source, because every captured operation infers the state Eager assigns and lowering preserves the arithmetic of each operation. Rotation hoisting is the exception: hoisted key switching rounds in a different order, so hoisted results differ from Eager within the CKKS error of the computation. Both results are deterministic.
Related concepts
- Compiler IR defines the module, dialects, value types, and materials.
- Compiled execution defines schedules, Graph segments, and result storage.
- Persistence and artifacts defines exported artifacts and value files.
- Value-state transitions defines the state the passes assign.