Compile a layer
Example source: examples/12_compile_layer.py
@fc.compile returns a CompiledCallable. The first call with a new input specialization captures the function as an MLIR module, runs the pass pipeline, lowers and links it on the Backend, and executes it; later compatible calls reuse the resident specialization. On CUDA, the callable captures CUDA Graphs of its schedule's capture-safe segments at the second execution of a specialization and keeps each Graph only where replay is faster (graph="auto", the default).
Example 12 compiles one encrypted dense layer
with a plaintext matrix float gain slots8192_scale40_depth7 (
Run the example
python examples/12_compile_layer.py
python examples/12_compile_layer.py --device cpu --size 8 --runs 52
The default device is cuda:0 when CUDA is available. The example prints the depth, scale, and clear-message error of each layer and gain, then the specialization counts, preparation seconds, steady call latency, cache status, and the CUDA Graph route of each specialization.
A layer as a class
from fhelium.algorithms import linear
def dense_transform(weights, slots):
size = weights.size(0)
rows = torch.arange(slots) % size
return linear.LinearTransform(
{-k: weights[rows, (rows + k) % size] for k in range(size)}, slots, name="dense")
class EncryptedLayer:
def __init__(self, engine, transform, like, keys, relinearization_key):
self.engine = engine
self.relinearization_key = relinearization_key
self.prepared = linear.prepare(engine, like, transform, keys=keys)
@fc.compile
def activate(self, value):
ntt = self.engine.coefficient_domain_to_ntt_domain(value)
return self.engine.relinearize(
self.engine.multiply(ntt, ntt), self.relinearization_key, rescale=True)
@fc.compile
def forward(self, x, gain: float = 1.0):
hidden = linear.apply(self.engine, x, prepared=self.prepared)
return self.engine.multiply_constant(self.activate(hidden), gain)2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
The vector LinearTransform stores diagonals torch.roll shift that aligns them:
linear.plan(transform) selects a baby-step/giant-step schedule, and plan.required_rotation_offsets(transform) lists the rotation keys it needs; the example creates them in one EvaluationKeySet. linear.prepare encodes the diagonals once for inputs with the depth, scale, and device of like; inside the compiled method, linear.apply(..., prepared=...) reads those plaintexts as materials and consumes one depth. The square activation relinearizes and rescales, and multiply_constant rescales once more, so the output is a two-component ciphertext at depth 3.
Methods, nested calls, and scalar arguments
A compiled method keeps one CompiledCallable per instance, with its own specializations; the two layers in the example each report two specializations. Capture reads instance attributes such as self.prepared as materials, which each call locates again on the instance.
forward calls the compiled activate. A compiled helper called during capture runs its source function on the traced arguments, so it is inlined and compiled under the options of the outer callable, and forward has one captured module and one schedule. Calling layer.activate(...) directly uses its own specializations.
Python scalars are static parameters. Each gain value selects its own specialization; a quantity that changes from call to call should be a Tensor or value argument. Specialization records value kind, shape, strides, dtype, device, CKKS state, and static scalar arguments; Tensor contents and storage addresses are not part of it, so a new ciphertext with the same state reuses the specialization.
Preparation, reuse, and statistics
stats = layer.forward.stats()
stats["prepare_seconds"], stats["resident_cache_hits"], stats["executions"]
stats["cache"] # source-cache eligibility
stats["graphs"] # one record per specialization and execution context2
3
4
prepare_seconds sums the stage timings of all specializations: capture, pipeline, lowering, linking, and scheduling. cache reports why the source cannot be found in the persistent cache before capture; in this example the source of fhelium.algorithms.linear contains a from ... import statement, which is outside the statically checked subset, so later processes find the entry by the key of the captured module instead, which skips the pipeline, lowering, and linking. Each record in graphs has a route state ("captured" after the capture, "warming" before it), its replay count, a fallback reason, and per-segment records whose choice is "graph", "direct", or "measuring".
layer.forward.prepare(x, 1.0) prepares a specialization without executing it, and clear() releases the resident specializations and their Graphs. Steady latency excludes the first two calls of each specialization: the first runs the prepared schedule, the second captures its Graph segments.
Inspect a specialization
variant = layer.forward.specializations[0]
variant.path # "compiled", "trace", or "source"
variant.timings # host seconds per stage
print(variant.compiled.captured.to_text()) # lowered and fused function2
3
4
path records whether the call compiled the specialization or loaded it from the persistent cache by the key of its captured module ("trace") or of its source ("source"). compiled holds the captured and linked function when the call compiled it.
Example 13 runs the same compiler stages with a caller-selected pipeline. Choose compile boundaries explains how function size, loops, scalars, and runtime decisions affect specializations, and Compile a callable lists the options of fc.compile.
Source
#!/usr/bin/env python3
"""Compile an encrypted dense layer with a square activation.
The layer is a class whose ``forward`` method is compiled per instance. It applies a prepared cyclic-diagonal linear transform from ``fhelium.algorithms.linear``, calls the compiled ``activate`` method, which is inlined into the caller, and multiplies by a Python ``float`` gain, which selects one specialization per value. The example then reads the callable's preparation, cache, execution, and CUDA Graph statistics.
"""
from __future__ import annotations
import argparse
import torch
from common import print_table, time_ms
from fhelium import CkksConfig, Preset, compile as fc
from fhelium.algorithms import linear
from fhelium.eager import Engine
from fhelium.values import Ciphertext, EvaluationKeySet, RelinearizationKey
def dense_transform(
weights: torch.Tensor, slots: int
) -> linear.LinearTransform:
"""Return ``x -> W x`` for ``x`` tiled with period ``W.size(0)`` across ``slots``."""
size = weights.size(0)
rows = torch.arange(slots) % size
# Diagonal -k pairs output slot j with input slot j + k, which
# torch.roll(x, shifts=-k) moves to slot j.
return linear.LinearTransform(
{-k: weights[rows, (rows + k) % size] for k in range(size)},
slots,
name="dense",
)
class EncryptedLayer:
"""``y = gain * (W x)^2`` for ``x`` tiled with period ``W.size(0)`` across all CKKS slots."""
def __init__(
self,
engine: Engine,
transform: linear.LinearTransform,
like: Ciphertext,
keys: EvaluationKeySet,
relinearization_key: RelinearizationKey,
) -> None:
self.engine = engine
self.relinearization_key = relinearization_key
# Diagonals are encoded once and read by every compiled call.
self.prepared = linear.prepare(engine, like, transform, keys=keys)
@fc.compile
def activate(self, value: Ciphertext) -> Ciphertext:
engine = self.engine
ntt = engine.coefficient_domain_to_ntt_domain(value)
return engine.relinearize(
engine.multiply(ntt, ntt), self.relinearization_key, rescale=True
)
@fc.compile
def forward(self, x: Ciphertext, gain: float = 1.0) -> Ciphertext:
hidden = linear.apply(self.engine, x, prepared=self.prepared)
return self.engine.multiply_constant(self.activate(hidden), gain)
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("--size", type=int, default=16)
parser.add_argument("--runs", type=int, default=20)
args = parser.parse_args()
device = torch.device(args.device)
config = CkksConfig.parse(Preset.slots8192_scale40_depth7)
engine = Engine(config, rng_seed=24)
secret_key = engine.create_secret_key(device=device)
public_key = engine.create_public_key(secret_key, device=device)
relinearization_key = engine.create_relinearization_key(
secret_key, device=device
)
size = args.size
generator = torch.Generator().manual_seed(12)
clear_x = 0.5 * torch.rand(size, generator=generator, dtype=torch.float64)
tiled_x = clear_x.repeat(config.num_slots // size).to(device)
x = engine.encrypt_message(tiled_x, public_key, device=device)
weights = [
0.2 * torch.randn(size, size, generator=generator, dtype=torch.float64)
for _ in range(2)
]
transforms = [dense_transform(w, config.num_slots) for w in weights]
steps = {
step
for transform in transforms
for step in linear.plan(transform).required_rotation_offsets(transform)
}
keys = EvaluationKeySet(
engine.create_rotation_key(step, secret_key, device=device)
for step in sorted(steps)
)
layers = [
EncryptedLayer(engine, transform, x, keys, relinearization_key)
for transform in transforms
]
rows = []
for index, (layer, w) in enumerate(zip(layers, weights, strict=True)):
for gain in (1.0, 0.5):
result = layer.forward(x, gain)
decoded = engine.decrypt_message(result, secret_key, is_real=True)
expected = gain * (w @ clear_x) ** 2
error = float((decoded[:size].cpu() - expected).abs().max())
rows.append(
[
index,
gain,
result.depth,
f"{result.scale:.6e}",
f"{error:.3e}",
]
)
print_table(["layer", "gain", "depth", "scale", "max abs error"], rows)
layer = layers[0]
steady, _ = time_ms(
lambda: layer.forward(x, 1.0), warmup=3, runs=args.runs, device=device
)
stats = layer.forward.stats()
print()
print_table(
["statistic", "value"],
[
["specializations of layer 0", len(layer.forward.specializations)],
[
"specializations of layer 1",
len(layers[1].forward.specializations),
],
["preparation seconds", f"{stats['prepare_seconds']:.3f}"],
["steady call mean ms", f"{steady['mean_ms']:.3f}"],
["resident cache hits", stats["resident_cache_hits"]],
["executions", stats["executions"]],
["source cache", stats["cache"] or "eligible"],
],
)
for record in stats["graphs"]:
segments = record["segments"]
print(
"Graph route:",
record["state"],
"replays:",
record["replays"],
"segments:",
[segment["choice"] for segment in segments],
"fallback:",
record["fallback_reason"],
)
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
158
159
160
161
162
163
164