Lowering, linking, and the Runner
A compiled specialization executes as one Runner schedule. fhelium/compile/mlir/_compile.py:compile_function produces it from the pipelined fhelium_ckks function in three steps: the lowering stage, by default default_lowering(arguments), hoists rotations, replaces CKKS operations by fhelium_rns and fhelium_ntt operations with fhelium-lower-ckks-to-rns, and groups residue arithmetic into fhelium_rns.fused regions with fhelium-fuse-rns; fhelium/compile/mlir/_link.py:link lowers each operation to an exec fragment through its Backend implementation, and LinkedFunction.schedule composes the fragments into one exec function that fhelium/backend/schedule.py translates into a torch.classes.fhelium.Runner. Eager calls the same implementations one fragment at a time. This article follows these steps and the storage, Graph, and transfer planning of the resulting schedule.
Lowering to RNS and NTT operations
fhelium-lower-ckks-to-rns (csrc/compiler/lib/Conversion/CKKSToRNS/CKKSToRNS.cpp) rewrites CKKS arithmetic, representation transitions, and key switches into RNS and NTT operations on residue Tensors. Each numerical table that a lowered operation reads, such as an NTT twiddle table, a rescale or basis-conversion parameter table, or a Galois permutation, becomes an fhelium_rns.table value whose description attribute names the table kind and its prime rows; the modulus chain attribute of the function supplies the primes. The pass option key-switches selects whether key switches are lowered into fhelium_rns.hybrid_modup_digit, fhelium_rns.key_switch_digit_product, and ModDown operations or kept as whole fhelium_ckks operations. fhelium-fuse-rns (csrc/compiler/lib/Dialect/RNS/Transforms/FuseRns.cpp) then forms fhelium_rns.fused regions of at most max-anchors anchor operations and names their fusion implementation: triton-ntt-fused for regions with NTT stages and triton-rns-fused otherwise. Coefficient automorphisms and row-reducing operations such as ModDown and rescale remain region boundaries.
fhelium.ir._operations.OPERATIONS catalogs every operation by its MLIR name with its effect and, for RNS and NTT operations, the residue structure (operand roles, result layout, and per-component arithmetic) that the generated kernels implement. The fusion pass and the Triton code generator read the same catalog.
Linking
backend_extension.link_plan walks the lowered entry in one native call (csrc/compiler/lib/Analysis/LinkPlan.cpp) and returns its operations grouped by lowering key, the operation name, attributes, and operand and result types, together with its root values: tables, materials, and arguments. link then:
- resolves each
fhelium_rns.tabledescription against the Backend resources of the argument device (table_tensors), sharing one Tensor between tables of different descriptions that read the same parameters, and eachfhelium_ckks.materialsymbol against the material table; - lowers each lowering key once per operand layout by calling the implementation that
registry.resolve(name, requested=...)returns, whererequestedis the operation'simplementationattribute, or the registry default when the attribute is absent; key switches,rotate_many, modulus raises, and scalar operations append the key-switch and parameter tables they read; afhelium_rns.fusedregion is lowered by its fusion implementation from afhelium.backend.fusion.FusedRegion, and a region the implementation does not accept runs its operations one by one; - traces each fragment on placeholders with its operands' layouts and uses the result layouts of the traced fragment for the fragments that consume them;
- compiles all Triton kernels of the fragments concurrently and runs the planned schedule (
LinkedFunction.schedule) once on the call's arguments; that run returns the first call's outputs, and its intermediates occupy the arena that later calls reuse.
An implementation's lower receives its Tensor operands as layout-carrying placeholders and writes ordinary PyTorch and native operator calls on them; fhelium/backend/lowering.py:ExecBuilder records each call as an exec operation. Calls of operators with a destination-passing overload (aten::name.out, or namespace::name_out with a written out argument for FHElium operators) are recorded as an allocation followed by a call of that overload, so that their results can live in the arena described below. An FHElium destination overload may also take a written byte workspace for the temporaries of the call; lowering queries its size with namespace::name_workspace_bytes, which reads only the sizes, strides, dtypes, devices, and option values of the functional arguments, and allocates a byte buffer that is live only during the call. Operators whose Tensor inputs are all link-time constants run once while lowering and become exec.constant buffers.
The returned LinkedFunction records, per operation, the fragment with its input and output slots; LinkedFunction.run executes the fragments in program order and releases each slot after its last use. LinkedFunction.schedule instantiates the fragments as one exec function (fhelium.backend.schedule.instantiate) whose arguments are the ciphertext payloads followed by the tables and materials, or which reads those constants as named materials for export, and translates it with schedule_functions. LinkedFunction.sources records for each constant whether it is a table description, a material symbol, or a table of a whole operation, so the compile cache and artifacts rebuild constants in a new process.
An exec.python_call runs a Python implementation inside the schedule: the Runner pauses at the instruction, the Python driver calls the function with the instruction's operands, and the execution resumes with the returned Tensors. A C++ caller builds and runs only schedules without Python calls.
fhelium.backend.lowering.Fragment.to_mlir prints a fragment as an exec function, and LinkedFunction.module holds the instantiated exec module after schedule.
Build and run an exec schedule in C++
<fhelium/runner.h> declares fhelium::exec::Runner, which executes an exec schedule: Tensor buffers, int64 and double host registers, and operations that call dispatcher operators, launch compiled device kernels, create views, allocate, copy and zero storage, call other schedules, and branch or loop on host registers. A program links FHElium::torch, builds a schedule with the builder methods, calls finalize(), and then calls run(inputs, integers, floats) any number of times. finalize resolves every operator schema through c10::Dispatcher and prepares the constant part of each argument stack, so a run fills only buffer Tensors and registers before each boxed call. Material and state buffers are bound once with bind; the Runner releases every other buffer when a run returns, apart from the outputs it returns.
#include <fhelium/runner.h>
using fhelium::exec::ArgumentKind;
constexpr auto buffer = static_cast<int64_t>(ArgumentKind::buffer);
// y = x + x mod q for residues x and a bound parameter table
auto runner = c10::make_intrusive<fhelium::exec::Runner>();
const auto x = runner->buffer("input", {}, {}, {}, {});
const auto table = runner->buffer("material", {}, {}, {}, {});
const auto y = runner->buffer("internal", {}, {}, {}, {});
runner->bind(table, params);
runner->inputs({x}, {}, {});
runner->outputs({y});
runner->call_op("fhelium_rns_ops::add_standard.default",
{buffer, buffer, buffer}, {x, x, table}, {y});
runner->finalize();
const auto result = runner->run({residues}, {}, {})[0];2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
A device kernel is registered as a KernelRecord: its image (cubin or PTX for CUDA, a code object for HIP), entry name, warp count and size, blocks per program, dynamic shared memory, runtime parameter types, and scratch sizes. The Runner loads the image with the CUDA runtime library API or the HIP module API on its first launch and launches it on the current stream of the selected device. A schedule that contains python_call operations runs only from Python, which supplies each call's results; run rejects it. Python builds the Runner of a schedule with torch.classes.fhelium.ScheduleCode (backend/runner.py:_realize), which decodes the schedule's builder calls in the artifact entry encoding with the decoder of loaded artifacts (csrc/runner/build.cpp), and runs it as torch.classes.fhelium.Runner. The repository example examples/cpp/runner_schedule.cpp builds a schedule with a host loop and a parity branch over fhelium_rns_ops operators and compares its result with direct libfhelium calls.
How long do intermediates live?
The native planner (csrc/compiler/lib/Schedule/SchedulePlanning.cpp) assigns the storage of a schedule when its first arena Runner is built. An allocation that is neither returned, carried through a loop or branch, nor returned by an operation that may alias its arguments becomes an arena buffer: a fixed view of one region per device that the Runner allocates once and keeps while it lives. Each arena buffer is live from the first to the last instruction that uses it or a view of it; a buffer first used before a loop and used inside it stays live until the loop ends. Buffers are placed largest first at the lowest 256-byte-aligned offset that does not overlap a buffer with an intersecting lifetime, and their allocation and release instructions are removed. The arena therefore holds the largest set of simultaneously live temporaries of the schedule. The Runners of top-level linked schedules on one CUDA device use that device's shared torch.classes.fhelium.Arena (backend/runner.py:shared_arena), which grows to the largest requirement among them; a growth makes each Runner derive its arena views again and drop its captures at its next execution, and the Arena orders executions that use it across streams. A schedule call's callee runs on a Runner with a private arena, because the caller's arena buffers stay live across the call. An execution that starts while another execution on the shared arena has not returned, through a Python implementation inside a schedule or from another thread, also uses a private-arena Runner of its schedule.
Allocations that reach the schedule results are output buffers allocated by each execution, and results of functional operator calls are internal buffers that the caching allocator provides. Each of these is released after its last use within its block; the returned outputs remain owned by the caller. Eager fragments do not use an arena, so their temporaries return to the caching allocator after each call. Tensor aliases and storage reclamation follow PyTorch ownership and allocator behavior.
PyTorch determines when released storage becomes reusable. Runtime-owned execution buffers and CUDA Graphs provide stable addresses and replay lifetimes when those properties are required.
A material buffer binds a live Tensor. In-place updates of its contents are visible to later executions; Specialization.update binds a replaced material object of the same layout without linking again.
How does a compiled callable reuse this work?
CompiledCallable in compile/_callable.py binds Python arguments, matches call signatures (compile/_specialization.py), and restores the output structure. Its Specialization (compile/mlir/_compile.py) holds the planned schedule function, its constant arguments with the recipes that derive them from Backend resources and materials, the materials and their MaterialGuard, the Preparation of the outlined preparation function, and the result states. The signature compares value kind, shape, strides, dtype, device, CKKS state, and static scalar values; ciphertext contents and storage addresses are not part of it.
A call whose signature has no resident specialization prepares one in the calling thread and then executes it, from the persistent cache when an entry matches (The compile cache) and by compile_function otherwise. A later call with the same signature locates its materials again; Specialization.update rebinds replaced materials of the bound layouts and reruns the preparation function when its inputs were replaced or modified. prepare(*args, **kwargs) establishes the matching specialization without executing it, and on_miss="error" requires a prior matching prepare.
Kernel compilation and automatic Graph capture
Linking compiles the Triton kernels of a specialization's fragments concurrently, using the launch signatures recorded during lowering, before their first execution; the Runner loads the compiled images when it is built.
With graph="auto" (the default) or graph=True, compile/_callable.py routes a specialization whose Tensor inputs share one CUDA device through a second Runner of the same schedule built with Graph segments, one for each grad, inference and autocast context. CPU inputs, inputs that require gradients and failures before the first capture continue as prepared calls; stats()["graphs"] records state, execution counts, capture costs, segment and replay counts and fallback reasons.
Capture safety is a static property of each schedule instruction. Kernel launches, views, allocations, copies, zeroing and operator calls whose Tensors are on one CUDA device are safe unless the operator carries torch.Tag.cudagraph_unsafe or reads device values on the host, such as aten::item or aten::nonzero; a schedule call is safe when its callee is. Collectives on CUDA buffers are safe; a segment runs directly when its process group cannot be captured. Python calls and CPU operations are unsafe. Planning encloses each maximal run of safe top-level instructions, where a loop or branch counts as one instruction, in a Graph segment. The Runner executes a segment at its first execution, captures it on a side stream at the second, and replays it afterwards. A Runner in mode auto (graph="auto") records events around the segment's first direct execution and its next three replays and, at the first execution after they have completed, keeps the Graph if the median replay is shorter than the direct execution; otherwise it releases the segment's captures and executes the segment directly from then on; the choice persists across later recaptures. Buffers that a segment reads from outside it, other than arena, material and state buffers and inputs held in storage owned by a Runner (its arena, output region or captured allocations), are staged into Runner-owned storage before each replay. An input held in Runner-owned storage is read in place; the Runner keeps up to four captures of a segment for different addresses of such inputs, captures a new address at its second occurrence and evicts the least recently replayed capture; host registers that a segment reads are recorded at capture, and a change captures the segments again. A rebound material that has the previous Tensor's address and layout keeps the captures; rebinding a material or state buffer to a Tensor at another address releases them.
With Graph segments, planning places each result allocated once with a static CUDA layout in the Runner's output region (place_output), which the Runner allocates at construction. The Runner returns such results, and results held in captured storage, as Tensors whose storage refers to the region without a copy. At the start of its next execution, before any instruction writes the region, it copies each previously returned result whose storage the caller still references into newly allocated memory and redirects that storage to the copy; views follow because they share the storage. Released results cost nothing. graph_stats counts these as detached_outputs. Allocations made inside segments by operations without a destination-passing form come from one Graph pool per device, shared by the Runners on that device's arena, whose executions never interleave; segments capture on one stream per device. Temporaries that a segment no longer reads are released after its replay; a result read after the segment and held in pool memory is copied into Runner-owned storage after each replay, which live_out_copies counts, so no pool memory outlives its Graph. Planning avoids these copies by placing such results in the arena or output region. private_pool_bytes reports the pool reservation. The Runner's segment_stats and the segments entry of stats()["graphs"] report each segment's node count, capture and instantiation host times and variant count; with fhelium.backend.runner.PROFILE_SEGMENTS set before the Runners are built, they also report the device times of the latest direct execution and replay. Clearing releases the Graph Runners, their pools and output regions and then the resident specializations. Persistent cache files remain intact.
Transfer and CPU-task planning
The same planner rewrites the top-level instructions of a schedule without adding or removing a transfer or collective and without changing the device of an operation. Every instruction keeps its order relative to the instructions it depends on, so results equal those of the synchronous schedule bitwise. A copy or aten::_to_copy between a CPU and a CUDA buffer of one dtype runs on a stream of role h2d or d2h, which first waits for an event of the compute stream. Device work that writes the device buffer or reads a host-to-device destination waits for the copy's event, and the host waits for it before it accesses the host buffer and before the schedule returns. A transfer is issued after the writers of its source and the earlier accesses of its destination, together with the allocation of its destination, at the earliest position at which the device memory the schedule needs exceeds that of the synchronous schedule by at most the size of its largest transfer. A device-to-host transfer whose source is in the arena delays the reuse of that arena range until the copy completes, within the same limit. A collective on buffers of one CUDA device runs on a stream of role comm in the same way, and Graph segments end at the stream instructions around it. Host buffers that the schedule allocates are page-locked; a caller-owned pageable buffer stays correct because CUDA stages it within the copy call, and its transfer overlaps only device work already queued.
A run of CPU instructions becomes a task on the process's CPU lane, one persistent worker thread shared by all schedules, which runs tasks in issue order and starts each task after the events of the transfers producing its inputs. Host-to-device transfers of a task's results are issued at the end of the task, and the host thread joins the task before it accesses a buffer the task accesses and before the schedule returns. Loops and branches are planned as single instructions with synchronous transfers. ScheduleFunction.plan holds the PlanReport of a planned schedule: arena bytes per device, arena buffer count, Graph segment count, output region bytes, and an OverlapReport of the moved transfers, the asynchronous transfers by direction, and the CPU tasks. Streams, events, and tasks are recorded in exported entries.
Preparation and execution statistics
stats()["specializations"] reports per specialization its path (compiled, trace, or source) and the host seconds of its stages (timings): capture, pipeline, preparation, lowering and fusion, linking, scheduling, material location, and cache load or store where those stages ran, together with execution, rebind, and preparation counts and the located and unlocated materials. resident_cache_hits counts calls served by a resident specialization.
Execution timing separates host dispatch from completed work. CPU calls complete on return. For inputs identifying one CUDA device, events measure the caller's CUDA stream, including work joined onto that stream; completed events are collected without a device synchronization. Use synchronized external timing for application-wide latency. timing separates compiled and steady compiled observations; the steady group excludes each specialization's first two calls, the initial execution and the automatic-capture transition. prepare_seconds sums the stage timings, and graph_capture_seconds records the additional Graph construction cost.
Generated kernels and fusion describes device code, and The compile cache describes persistent entries.