Export and load a compiled callable
Example source: examples/15_compile_export_load.py
fhelium.compile.export writes the linked execution of a compiled callable for a set of call signatures to one artifact file. fhelium.compile.load reads the file in another process and returns a callable that runs without capture, transformation, linking, or Triton compilation. Example 15 separates the two roles of an encrypted service: a client that owns the secret key and a server that holds only the artifact, the evaluation keys, and the per-call inputs.
Run the example
python examples/15_compile_export_load.py
python examples/15_compile_export_load.py --device cpu --output-dir /tmp/fhelium-export2
The client writes layer.fhelium, the rotation key file, the encrypted input, and the weight Tensor as weight.fhelium, starts the server as a separate Python process, and decrypts the server's output.fhelium. It prints the file sizes and the result depth, scale, and error. With --output-dir, the files remain and the example prints a command line for examples/cpp/load_artifact that reads the same artifact, key, input, and weight.
Client: compile and export
declared_key = engine.declare_key(RotationKey, rotation_step=1)
@fc.compile
def layer(value: Ciphertext, weight: torch.Tensor) -> Ciphertext:
plain = engine.prepare_compressed_plaintext(weight, depth=value.depth, device=value.device)
rotated = engine.add(value, engine.rotate_with_key(value, declared_key))
product = engine.multiply_plaintext(engine.coefficient_domain_to_ntt_domain(rotated), plain)
return engine.rescale_to_next_depth(engine.ntt_domain_to_coefficient_domain(product))
fc.export(layer, artifact, signatures=[(x, weight)], overwrite=True)
fh.save_value(rotation_key, directory / "key-rotation-1.fhelium", overwrite=True)
fh.save_value(x, directory / "input.fhelium", overwrite=True)
save_container(directory / "weight.fhelium", {"0": weight}, {}, overwrite=True)2
3
4
5
6
7
8
9
10
11
12
13
layer computes
engine.declare_key(RotationKey, rotation_step=1) returns a rotation key with the prime rows and digit partition that create_rotation_key(1, ...) produces and its data on the meta device, so the function is compiled against the key's layout without key data or a secret key. signatures lists example calls; export compiles each one without running it and stores its planned schedule as entry call<i> together with a copy planned with CUDA Graph segments. The rotation key is recorded as a key material with its role and prime and digit layout, and the client saves its generated rotation key as a separate value file.
The compressed plaintext of the weight does not depend on the ciphertext, so compilation outlines its encoding into the preparation function. The preparation function reads the weight argument, so export writes it as the per-call preparation entry call0.prepare, whose input is the caller's weight Tensor and whose output is the prepared plaintext that call0 reads.
Server: load and call
keys = [fh.load_value(path, device=device) for path in sorted(directory.glob("key-*.fhelium"))]
layer = fc.load(directory / "layer.fhelium", keys=keys, device=device)
x = fh.load_value(directory / "input.fhelium", device=device, expected_type=Ciphertext)
weight = load_container(directory / "weight.fhelium", device)[0]["0"]
fh.save_value(layer(x, weight), directory / "output.fhelium", overwrite=True)2
3
4
5
The server runs in its own process and never sees the secret key or the source of layer. fc.load matches each key object to the key materials recorded in the artifact by role and layout; a key read from a value file is compact and is expanded on its device before binding. Loading runs the artifact's table entry once, which builds the NTT, RNS, and key-switching tables on the server's device, and returns a LoadedFunction. A call selects the stored signature whose argument conditions match and raises SpecializationMiss when none matches. Before running call0, the loaded function runs call0.prepare on the weight when that Tensor was replaced or modified since the last preparation, as its version counter records.
Plaintext encoding and real-scalar arithmetic in the loaded entries round with a random stream per device, seeded from the operating system unless fc.load(..., seed=s) derives it as Engine(rng_seed=s) does on that device. With the same seed, the Python and C++ loaders produce bitwise equal outputs.
Client: decrypt
The client reads output.fhelium and decrypts it with its secret key. The artifact dominates the file sizes: it contains the planned schedules, the preparation entry, kernel images, and the builder calls of the tables; the rotation key file is the next largest.
Deploy a compiled callable describes the export options, key matching, per-call preparation, and the C++ loading interface.
Source
#!/usr/bin/env python3
"""Export a compiled function to one file and call it in another process.
The layer is compiled against a rotation key declared by role and layout (``Engine.declare_key``), so exporting it with ``fhelium.compile.export`` reads no key data. Its weight is a Tensor argument that the layer encodes, which the artifact stores as a per-call preparation entry. The client process holds the secret key and writes its evaluation key, an encrypted input and the weight as files. A separate server process loads the artifact with ``fhelium.compile.load``, binds the client's key from its file, calls the layer with the weight, and writes the encrypted result, which the client decrypts. The same artifact and files are accepted by ``examples/cpp/load_artifact``.
"""
from __future__ import annotations
import argparse
import subprocess
import sys
import time
from contextlib import nullcontext
from pathlib import Path
from tempfile import TemporaryDirectory
import torch
from common import print_table
import fhelium as fh
from fhelium import compile as fc
from fhelium.eager import Engine
from fhelium.native.artifact import load_container, save_container
from fhelium.values import Ciphertext, RotationKey
_SIZE = 16
def serve(directory: Path, device: str) -> None:
"""Load the artifact and evaluate the stored input; no secret key is present."""
started = time.perf_counter()
keys = [
fh.load_value(path, device=device)
for path in sorted(directory.glob("key-*.fhelium"))
]
layer = fc.load(directory / "layer.fhelium", keys=keys, device=device)
loaded = time.perf_counter() - started
x = fh.load_value(
directory / "input.fhelium", device=device, expected_type=Ciphertext
)
weight = load_container(directory / "weight.fhelium", device)[0]["0"]
result = layer(x, weight)
fh.save_value(result, directory / "output.fhelium", overwrite=True)
print(f"server: loaded the artifact in {loaded:.3f} s")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--device", default="cuda:0" if torch.cuda.is_available() else "cpu"
)
parser.add_argument(
"--output-dir",
type=Path,
help="Keep the artifact and value files here; otherwise use a temporary directory.",
)
parser.add_argument("--serve", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args()
if args.serve is not None:
serve(args.serve, args.device)
return
device = torch.device(args.device)
config = fh.CkksConfig.parse(fh.Preset.slots8192_scale40_depth7)
engine = Engine(config, rng_seed=15)
declared_key = engine.declare_key(RotationKey, rotation_step=1)
@fc.compile
def layer(value: Ciphertext, weight: torch.Tensor) -> Ciphertext:
plain = engine.prepare_compressed_plaintext(
weight, depth=value.depth, device=value.device
)
rotated = engine.add(value, engine.rotate_with_key(value, declared_key))
product = engine.multiply_plaintext(
engine.coefficient_domain_to_ntt_domain(rotated), plain
)
return engine.rescale_to_next_depth(
engine.ntt_domain_to_coefficient_domain(product)
)
# The client's keys; the artifact binds them when it is loaded.
secret_key = engine.create_secret_key(device=device)
public_key = engine.create_public_key(secret_key, device=device)
rotation_key = engine.create_rotation_key(1, secret_key, device=device)
weight = torch.linspace(0.1, 0.2, _SIZE, dtype=torch.float64, device=device)
clear = torch.linspace(-0.2, 0.3, _SIZE, dtype=torch.float64)
x = engine.encrypt_message(
clear.repeat(config.num_slots // _SIZE), public_key, device=device
)
context = (
TemporaryDirectory(prefix="fhelium-export-")
if args.output_dir is None
else nullcontext(args.output_dir)
)
with context as root:
directory = Path(root)
directory.mkdir(parents=True, exist_ok=True)
artifact = directory / "layer.fhelium"
fc.export(layer, artifact, signatures=[(x, weight)], overwrite=True)
fh.save_value(
rotation_key, directory / "key-rotation-1.fhelium", overwrite=True
)
fh.save_value(x, directory / "input.fhelium", overwrite=True)
save_container(
directory / "weight.fhelium", {"0": weight}, {}, overwrite=True
)
subprocess.run(
[
sys.executable,
__file__,
"--serve",
str(directory),
"--device",
args.device,
],
check=True,
)
result = fh.load_value(
directory / "output.fhelium",
device=device,
expected_type=Ciphertext,
)
decoded = engine.decrypt_message(result, secret_key, is_real=True)
expected = (clear + torch.roll(clear, shifts=1)) * weight.cpu()
error = float((decoded[:_SIZE].cpu() - expected).abs().max())
print_table(
["file", "bytes"],
[
[path.name, path.stat().st_size]
for path in sorted(directory.iterdir())
],
)
print_table(
["result", "value"],
[
["depth", result.depth],
["scale", f"{result.scale:.6e}"],
["max abs error", f"{error:.3e}"],
],
)
if args.output_dir is not None:
print(
"C++: load_artifact --tensors",
directory / "weight.fhelium",
artifact,
directory / "output-cpp.fhelium",
directory / "input.fhelium",
directory / "key-rotation-1.fhelium",
)
if __name__ == "__main__":
main()2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157