Linear layer and polynomial activation
Example source: examples/08_algorithms_linear_polynomial.py
This example evaluates one encrypted network layer fhelium.algorithms.linear, followed by a Chebyshev approximation fhelium.algorithms.polynomial. The same Python function runs directly on the Engine and under fc.compile, and the example compares their depth, scale, error, and latency.
Run the example
python examples/08_algorithms_linear_polynomial.py
python examples/08_algorithms_linear_polynomial.py --device cuda:0 --features 32 --degree 312
--features sets the matrix width --degree sets the Chebyshev degree of the activation.
1. Represent the matrix as cyclic diagonals
The input vector torch.roll(..., shifts=k) and places
every period of
weight_diagonals builds this mapping from rotation offset to slot vector, and linear.LinearTransform(diagonals, slots, name="dense") records it. The transform contains plaintext data only; it holds no keys or encoded plaintexts.
2. Plan the evaluation and provision keys
linear.plan(transform) returns a baby-step giant-step (BSGS) plan. With baby step
so the evaluator performs about
linear_plan = linear.plan(transform)
steps = linear_plan.required_rotation_offsets(transform)
keys = EvaluationKeySet(
[engine.create_rotation_key(step, secret_key) for step in steps]
+ [engine.create_relinearization_key(secret_key)]
)2
3
4
5
6
For
3. Fit the activation
polynomial.chebyshev_fit(gelu, degree) interpolates GELU at Chebyshev nodes on Polynomial with Chebyshev coefficients
max_error reports the interpolation error sampled on the interval. The approximation is valid only for inputs in polynomial.plan(activation) selects the evaluation schedule, and activation_plan.required_depths(activation) reports the depth it consumes; the degree-15 schedule consumes five depths.
4. Prepare once, then evaluate
linear.prepare encodes the shifted diagonals
prepared = linear.prepare(engine, x, transform, keys=keys)
def layer(value):
hidden = linear.apply(engine, value, prepared=prepared)
return polynomial.evaluate(engine, hidden, activation, activation_plan, keys=keys)2
3
4
5
Diagonal encoding draws stochastic-rounding samples. Preparing outside layer encodes once and reuses the same plaintexts for every call, Eager or compiled. linear.apply consumes one depth: the plaintext products are followed by one rescale. polynomial.evaluate multiplies ciphertexts, relinearizes the products, and rescales according to its plan.
5. Compile the same function
fc.compile(layer) captures the Engine calls of layer, including those inside linear.apply and polynomial.evaluate. The prepared plaintexts and keys become materials of the captured module, located again on each call, so the compiled callable performs no key generation or encoding at call time. The first call compiles for the input's value state; later calls with the same state reuse the compiled function.
6. Read the output
The example prints the depth and actual scale after each step:
| value | depth | log2 scale |
|---|---|---|
| input | 0 | 44.976 |
| 1 | 40.008 | |
| 6 | 40.014 | |
| 6 | 40.014 |
These values are from the default slots8192-scale40-depth7 preset,
The final table reports the mean and minimum latency of repeated layer(x) and compiled_layer(x) calls with CUDA synchronization.
Source
#!/usr/bin/env python3
"""Evaluate a linear layer and a Chebyshev polynomial activation, Eagerly and compiled.
The layer computes ``y = W x`` on a packed vector with
``fhelium.algorithms.linear`` and then ``z = p(y)`` slot-wise with
``fhelium.algorithms.polynomial``, where ``p`` is a Chebyshev interpolant of
the GELU activation on ``[-1, 1]``. The same Python function runs directly on
the Engine and under ``@fc.compile``.
Run:
python examples/08_algorithms_linear_polynomial.py
python examples/08_algorithms_linear_polynomial.py --device cuda:0
"""
from __future__ import annotations
import argparse
import math
import numpy as np
import torch
from common import (
add_engine_args,
error_stats,
format_bytes,
make_engine,
print_table,
time_ms,
)
from fhelium import compile as fc
from fhelium.algorithms import linear, polynomial
from fhelium.values import EvaluationKeySet
def gelu(t: np.ndarray) -> np.ndarray:
"""Return the tanh form of GELU, the activation approximated by ``p``."""
return (
0.5
* t
* (1.0 + np.tanh(math.sqrt(2.0 / math.pi) * (t + 0.044715 * t**3)))
)
def weight_diagonals(weight: np.ndarray, slots: int) -> dict[int, np.ndarray]:
r"""Return the cyclic diagonals of ``weight`` for a periodically packed vector.
With slots holding $x_{j \bmod n}$, rotation by $k$ (``torch.roll`` with
``shifts=k``) places $x_{(i-k) \bmod n}$ in slot $i$, so
$d_k[i]=W_{i \bmod n,\,(i-k) \bmod n}$ gives
$\sum_k d_k\odot\operatorname{Rot}_k(x)=Wx$ in every period.
"""
n = weight.shape[0]
rows = np.arange(slots) % n
return {
step: weight[rows, (rows - step) % n].astype(np.complex128)
for step in range(n)
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_engine_args(parser, default_preset="slots8192-scale40-depth7")
parser.add_argument(
"--features", type=int, default=16, help="Width n of the n x n weight."
)
parser.add_argument(
"--degree",
type=int,
default=15,
help="Chebyshev degree of the activation.",
)
args = parser.parse_args()
engine = make_engine(args)
slots = engine.num_slots
n = args.features
generator = np.random.default_rng(8)
# Rows of W have unit L1 norm, so |W x| <= 1 for |x| <= 1: the layer
# output stays inside the activation's interpolation interval.
weight = generator.uniform(-1.0, 1.0, (n, n))
weight /= np.abs(weight).sum(axis=1, keepdims=True)
features = generator.uniform(-1.0, 1.0, n)
expected = gelu(weight @ features)
transform = linear.LinearTransform(
weight_diagonals(weight, slots), slots, name="dense"
)
linear_plan = linear.plan(transform)
activation = polynomial.chebyshev_fit(gelu, args.degree, name="gelu")
activation_plan = polynomial.plan(activation)
# Key provisioning: the linear plan reports its rotation steps and the
# polynomial needs one relinearization key.
device = torch.device(args.device)
secret_key = engine.create_secret_key(device=device)
public_key = engine.create_public_key(secret_key)
steps = linear_plan.required_rotation_offsets(transform)
keys = EvaluationKeySet(
[engine.create_rotation_key(step, secret_key) for step in steps]
+ [engine.create_relinearization_key(secret_key)]
)
x = engine.encrypt_message(
torch.as_tensor(
np.resize(features, slots), dtype=torch.float64, device=device
),
public_key,
)
# Encode the diagonals and select keys once for inputs with x's state.
prepared = linear.prepare(engine, x, transform, keys=keys)
def layer(value):
hidden = linear.apply(engine, value, prepared=prepared)
return polynomial.evaluate(
engine, hidden, activation, activation_plan, keys=keys
)
compiled_layer = fc.compile(layer)
hidden = linear.apply(engine, x, prepared=prepared)
eager = polynomial.evaluate(
engine, hidden, activation, activation_plan, keys=keys
)
compiled = compiled_layer(x)
print(
f"Preset {args.preset}, {n} x {n} weight, {len(steps)} rotation keys "
f"({format_bytes(sum(key.data.nbytes for key in keys))} of evaluation keys)"
)
print(
f"BSGS baby step {linear_plan.baby_step}; activation degree {activation.degree}, "
f"sampled interpolation error {activation.max_error:.2e}"
)
print_table(
["value", "depth", "log2 scale"],
[
["input", x.depth, f"{math.log2(x.scale):.3f}"],
["W x", hidden.depth, f"{math.log2(hidden.scale):.3f}"],
["p(W x), Eager", eager.depth, f"{math.log2(eager.scale):.3f}"],
[
"p(W x), compiled",
compiled.depth,
f"{math.log2(compiled.scale):.3f}",
],
],
)
print(
f"depths consumed: linear {linear_plan.required_depths(transform)}, "
f"activation {activation_plan.required_depths(activation)}"
)
rows = []
for label, value in (("Eager", eager), ("compiled", compiled)):
decoded = engine.decrypt_message(value, secret_key, is_real=True).cpu()
error = error_stats(decoded[:n], torch.as_tensor(expected))
rows.append([label, f"{error['max_abs']:.3e}", f"{error['rms']:.3e}"])
print_table(["path", "max abs error", "rms error"], rows)
eager_time, _ = time_ms(lambda: layer(x), device=device)
compiled_time, _ = time_ms(lambda: compiled_layer(x), device=device)
print_table(
["path", "mean ms", "min ms"],
[
[
"Eager",
f"{eager_time['mean_ms']:.2f}",
f"{eager_time['min_ms']:.2f}",
],
[
"compiled",
f"{compiled_time['mean_ms']:.2f}",
f"{compiled_time['min_ms']:.2f}",
],
],
)
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185