Deploy a compiled callable
fhelium.compile.export writes the planned execution of a compiled callable for a set of call signatures to one artifact file: Runner schedules, kernel images, link-time constants, the builder calls that produce its tables, and the materials it embeds. fhelium.compile.load in Python and fhelium::Artifact in C++ run that file in another process without capture, the MLIR compiler, linking, or Triton compilation. Keys are not stored in the artifact; the loading process supplies them.
Prerequisites
The exporting and loading processes use the same FHElium native library and Triton version; the artifact records both, and loading an artifact with a different identity raises an error naming the differing field. The loading device has the CUDA architecture of the exporting device, or the artifact contains kernel images for it (targets below). The loading process has the evaluation keys of the computation, for example as value files written with fhelium.save_value.
1. Compile and export
import torch
import fhelium as fh
from fhelium import compile as fc
from fhelium.eager import Engine
from fhelium.values import RotationKey
engine = Engine(fh.CkksConfig.parse(fh.Preset.slots8192_scale40_depth7))
secret = engine.create_secret_key(device="cuda")
public = engine.create_public_key(secret, device="cuda")
rotation = engine.declare_key(RotationKey, rotation_step=1)
x = engine.encrypt_message(torch.linspace(-0.02, 0.03, 16), public, device="cuda")
weight = torch.linspace(0.1, 0.2, 16, dtype=torch.float64, device="cuda")
@fc.compile
def layer(value, weight):
plain = engine.prepare_compressed_plaintext(weight, depth=value.depth, device=value.device)
rotated = engine.add(value, engine.rotate_with_key(value, rotation))
return engine.multiply_plaintext(engine.coefficient_domain_to_ntt_domain(rotated), plain)
fc.export(layer, "layer.fhelium", signatures=[(x, weight)])
fh.save_value(engine.create_rotation_key(1, secret, device="cuda"), "key-rotation-1.fhelium")2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
engine.declare_key(role, rotation_step=..., source_depth=0, digit_prime_ids=None, p_prime_ids=None) returns a RotationKey, RelinearizationKey, or ConjugationKey with the prime rows and digit partition that the matching create_*_key call produces and its data on the meta device. It needs no secret key. Export compiles against such a key wherever the function reads one, as an argument or from its closure, globals, or bound objects; the generated key with the same role and layout is bound when the artifact is loaded. The example ciphertext supplies the signature of the call: its depth, scale, layout, and device. Generated keys work in the same way; export reads only their layouts. A compact key raises ExportError; expand it with KeySwitchKey.expand first.
signatures lists example calls, as positional-argument sequences or keyword mappings. Each one is compiled without the callable's caches and without running it, and stored as entry call<i>, together with entry call<i>.graphs, the same schedule planned with CUDA Graph segments, for CUDA examples.
| Option | Effect |
|---|---|
targets=("sm_90",) | Adds kernel images compiled for further CUDA architectures; every kernel also stores the image of the exporting device and its PTX. |
overwrite=True | Replaces an existing file. |
The materials of each entry are recorded by binding:
| Binding | Materials |
|---|---|
caller | Keys, with their role and prime and digit layout; the random rounding state of each device, which plaintext encoding and real-scalar arithmetic advance |
built | NTT, RNS, and key-switching tables: the artifact stores the registered builder calls that produce them, and the loader runs those calls once on fresh Backend resources of its device |
embedded | Prepared plaintexts of weights that the function reads from its closure or bound objects, and other Tensors and plaintexts the function reads |
prepare | Prepared plaintexts computed from call arguments by the per-call preparation entry |
When the preparation function reads a material located in the call arguments, such as the weight argument above, export writes it as the per-call preparation entry call<i>.prepare. Its inputs are the caller's Tensors and the embedded materials it reads, and its outputs are the prepare materials that call<i> reads. A preparation function that reads only materials of the function runs during export, and its results are embedded.
Export raises fhelium.compile.ExportError when a schedule calls Python, when the examples use Engines of different CKKS configurations, or when an example call reads a compact key.
2. Load and call in Python
keys = [fh.load_value("key-rotation-1.fhelium", device="cuda")]
loaded = fc.load("layer.fhelium", keys=keys)
result = loaded(x, weight)2
3
keys supplies key objects, which are matched to the key records of the artifact by role and layout, or a mapping from the artifact's key symbols to keys; loading fails when a declared key has no match. A compact key read from a value file is expanded on its device before binding. device places the artifact's CUDA devices, as described below, graph takes the values of the graph option of fc.compile (default "auto"), and groups maps the process-group symbols of an artifact with collectives to torch.distributed process groups. The default group is recorded as world and binds to the torch.distributed WORLD group without an entry in groups; torch.distributed is initialized before such an artifact is loaded. An artifact records a process rank when the exported function read the rank during capture; loading it on another rank raises RuntimeError, and other artifacts load on every rank of the group. seed derives the rounding stream of each device as Engine(rng_seed=seed) derives it; the default None seeds it from the operating system.
The artifact records its execution device, the device the Ciphertext arguments of the example calls lay on, and every further CUDA device that its entries, constants, and materials use, such as a device the exported function moved a Tensor to. Loading places these devices by a device mapping, in the manner of torch.load(map_location=...):
device | Placement |
|---|---|
None (default) | The execution device runs on the current CUDA device; other devices keep their index. |
"cuda:1" | The execution device runs on cuda:1, as {<execution device>: "cuda:1"}; other devices keep their index. |
{"cuda:0": "cuda:2", "cuda:1": "cuda:3"} | Each named artifact device runs on the device it maps to; unnamed devices, including the execution device, keep their index. |
Keys and values of a mapping are indexed CUDA devices, and the CPU stays the CPU. A function exported with Tensors on two GPUs therefore uses two GPUs after loading. When a placed device does not exist in the loading process, fc.load raises ValueError naming the artifact device and suggesting a mapping such as device={"cuda:1": "cuda:0"}; a two-GPU artifact loaded on a one-GPU machine needs such a mapping. loaded.devices maps each artifact device to the device it runs on, the execution device first:
loaded = fc.load("layer.fhelium", keys=keys, device={"cuda:0": "cuda:1", "cuda:1": "cuda:0"})
loaded.devices # {device('cuda:0'): device('cuda:1'), device('cuda:1'): device('cuda:0')}2
Ciphertext arguments lie on the placed execution device, and keys are supplied there.
Loading runs the artifact's tables entry once. A call selects the stored signature whose argument conditions match and raises SpecializationMiss when none matches. Embedded materials that were located in the call arguments are bound from each call's arguments. A signature with a preparation entry runs it before the call when one of the Tensors it reads was replaced or modified since its last run, as the Tensor version counters record; with seed=s, its encoding draws the rounding stream that Engine(rng_seed=s) draws on that device. loaded.bind({symbol: tensor}) replaces another embedded material with a Tensor of the declared shape, dtype, and device, and loaded.bind_key(key) binds a key to every key material whose role and layout it matches.
3. Load and call in C++
A C++ program links FHElium::torch as described in Call the native library from C++ and loads the same file with fhelium::Artifact from <fhelium/artifact.h>:
#include <fhelium/artifact.h>
#include <fhelium/container.h>
#include <fhelium/values.h>
const torch::Device device(torch::kCUDA, 0);
auto artifact = c10::make_intrusive<fhelium::Artifact>("layer.fhelium", device);
for (const auto& path : key_paths)
artifact->bind_key(fhelium::io::load_value(path, device));
artifact->prepare();
const auto signature = artifact->signatures().at(0);
if (!signature.prepare.empty()) {
const auto weight = fhelium::io::load_container("weight.fhelium", device).tensors.at(0).second;
artifact->refresh(signature.prepare, {weight});
}
auto runner = artifact->runner(signature.entry, std::nullopt, "auto", false);
const auto input = fhelium::io::load_value("input.fhelium", device);
auto result = signature.results.at(0);
result.tensors["data"] = runner->run({input.tensors.at("data")}, {}, {}).at(0);
fhelium::io::save_value("output.fhelium", result, false, true);2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Artifact(path, device) places the artifact's execution device on CUDA device device and keeps the index of its other devices; an artifact exported on the CPU stays there. Artifact(path, devices) takes a fhelium::DeviceMap, a list of (artifact device, device) pairs, and places each listed device as fc.load places a mapping:
const fhelium::DeviceMap swap{{torch::Device("cuda:0"), torch::Device("cuda:1")},
{torch::Device("cuda:1"), torch::Device("cuda:0")}};
auto swapped = c10::make_intrusive<fhelium::Artifact>("layer.fhelium", swap);
const torch::Device execution = swapped->devices().front().second;2
3
4
devices() returns each artifact device with the device it is placed on, the execution device first. Both constructors raise the fc.load error for a placed device that the process does not have. The constructor rejects files written by a library with a different FHElium version, operator schema hash, Torch ABI, or CUDA runtime. bind_key binds a key value to every declared key material whose role is the value type and whose layout (prime rows, digit rows, basis, domain, residue representation, and, for rotation keys, the step) equals the value's metadata; a compact key is expanded on the device first, and a key the artifact does not use binds nothing. seed_rounding(seed) seeds the rounding streams from seed as Engine(rng_seed=seed) does, or from the operating system for std::nullopt; prepare seeds the rounding streams that are still unbound from the operating system and builds the recorded tables once. bind(symbol, tensor) replaces a material by symbol. signatures() lists each recorded call with its entry, the value type and metadata of its results, and, for a call with per-call preparation, the entry name prepare and the number prepare_arguments of caller Tensors it reads. refresh(name, arguments) runs that preparation entry on the caller Tensors and writes its outputs into their materials, at the addresses that the Runners and their captured Graphs read; call it after prepare and whenever the argument Tensors change. runner(entry, arena, graphs, profile) returns a finalized Runner whose inputs are the argument Tensors in signature order. bind_group(symbol, name) or bind_group(symbol, group) binds a process-group symbol of an artifact with collectives to a registered c10d group name or a c10d::ProcessGroup before Runners are built.
The repository example examples/cpp/load_artifact.cpp takes [--seed SEED] [--tensors FILE] [--device DEVICES] ARTIFACT OUTPUT INPUT KEY...: an optional seed for the rounding streams, a container written by fhelium.native.artifact.save_container that holds the per-call Tensors of the preparation entry in name order, the artifact, an output path, the input value file, and the key value files. DEVICES is a device such as cuda:1 or a mapping such as cuda:0=cuda:1,cuda:1=cuda:0; by default the execution device is placed on cuda:0. It runs the preparation entry on those Tensors and the first signature with automatic CUDA Graph selection, and writes the result as a value file that fhelium.load_value reads. Example 15 writes a matching artifact, key file, input, and weight file.
Verify the outcome
Decrypt the loaded callable's result with the client's secret key and compare it with the result of the compiled callable in the exporting process. Compiled artifact format describes the manifest, entries, and material bindings.