Bootstrap a full-slot CKKS ciphertext
Example source: examples/25_experimental_bootstrap.py
FHElium composes bootstrapping from modulus raising, Fourier transforms and periodic reduction. A configured FullSlotBootstrap is callable, exposes its depth and scale schedule, and supports prepared execution. cosine_bootstrap assembles common component combinations; its profiles are starting points that can be replaced or customized.
This tutorial constructs both centered raising and sparse-secret encapsulation, then uses the same key inventory, execution and verification workflow. The composition guide covers component replacement. The mathematical model defines the coordinates and state transitions.
1. Choose the construction
The complete refresh follows:
entry coordinates → modulus raising → CoeffsToSlots
→ periodic reduction → SlotsToCoeffs → output compensation2
CenteredModRaise extends the centered CRT representative of each component under the main secret. EncapsulatedModRaise switches to an intermediate secret in a low basis, extends the centered components and returns to the main secret before the Fourier transforms. A sparse intermediate secret changes the integer phase range that the subsequent periodic reduction must handle.
The cosine profiles select the following circuit components:
| Profile | Raw coordinate bound B | Seed degree | Double-angle iterations | CoeffsToSlots stages | SlotsToCoeffs stages | Default polynomial evaluation |
|---|---|---|---|---|---|---|
7/44 | 1024 | 44 | 7 | 2 | 2 | Blocked |
8/28 | 1024 | 28 | 8 | 2 | 2 | Binary |
8/28-s2c3 | 1024 | 28 | 8 | 2 | 3 | Binary |
3/30 | 32 | 30 | 3 | 4 | 3 | Even decomposition with Blocked evaluation |
A profile does not choose the secret distribution or generate keys. Select the modulus chain, raising relation, coordinate range and scale schedule together. The degree-30 profile uses a narrower range; selecting its name alone does not enable sparse-secret encapsulation.
Centered raising
The following configuration uses int64 residues, generator five and a default scale of approximately
import torch
import fhelium as fh
from fhelium.eager import Engine
from fhelium.experimental import bootstrap as bs
from fhelium.values import EvaluationKeySet
torch.set_default_device("cuda:0")
config = fh.CkksConfig.parse(
fh.Preset.slots32768_scale50_depth27_int64,
galois_generator=5,
)
engine = Engine(config, allow_automatic_key_generation=False)
secret_key = engine.create_secret_key()
bootstrap = bs.cosine_bootstrap(engine)2
3
4
5
6
7
8
9
10
11
12
13
14
The default 7/44 composition uses Blocked Chebyshev evaluation and aggregate giant-step quotients. Its default source basis is the terminal Q group; entry begins at the preceding group and uses integer scale lifting followed by rescale.
Sparse-secret encapsulation
For an executable example from the repository root:
python examples/25_experimental_bootstrap.py --encapsulatedThe example compiles the complete prepared callable by default and provisions all required direct rotations. --eager selects Eager execution; --core-graph selects the normalized-core Graph example. The cosine composition selects weighted-product implementations with "auto" and a chunk size of 16. CUDA contexts use the group-16 compact Montgomery NTT policy unless the caller supplies another policy.
The example defines prime groups and per-depth scale targets in examples/_bootstrap_encapsulation_parameters.py. It uses profile="3/30" choice specifies the approximation profile; the example supplies these modulus and scale parameters separately.
From the repository root, the same construction can be assembled as follows. This block replaces the centered configuration above; the remaining tutorial steps apply to either choice.
from examples._bootstrap_encapsulation_parameters import parameters
config, auxiliary, target_scales = parameters()
engine = Engine(
config,
rns_dtype=torch.int32,
allow_automatic_key_generation=False,
)
secret_key = engine.create_secret_key(hamming_weight=config.N // 2)
intermediate = engine.create_secret_key(hamming_weight=32)
low_key, return_key = engine.create_encapsulation_keys(
secret_key, intermediate, **auxiliary
)
raising = bs.EncapsulatedModRaise(low_key, return_key, **auxiliary)
del intermediate
bootstrap = bs.cosine_bootstrap(
engine,
profile="3/30",
modulus_raising=raising,
input_depth=engine.max_depth,
target_scales=target_scales,
product_implementation="auto",
)2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
The low switch changes the relation from main secret EncapsulatedModRaise retains the two evaluation-key values, not either secret. An intermediate secret need not be regenerated for every refresh; the supplied evaluation material can be reused.
hamming_weight=h samples exactly --intermediate-secret-weight changes it, and the reducer range must be assessed for the resulting construction. The low Q/P relation, return hint and their joint publication determine the relevant security assumptions. The main QP budget check alone does not assign a security level to that combination; see Sparse-secret encapsulation.
The degree-30 seed is even after a coordinate shift. EvenChebyshevEvaluator uses
2. Provision the shared evaluation keys
After selecting either construction, create the encryption key and populate an application-owned inventory for the bootstrap:
public_key = engine.create_public_key(secret_key)
evaluation_keys = EvaluationKeySet()
bootstrap.create_evaluation_keys(
secret_key,
into=evaluation_keys,
device=secret_key.device,
)2
3
4
5
6
7
EvaluationKeySet retains ordinary rotation, relinearization and conjugation key values. Its constructor accepts an iterable, and add and update retain references with object-identity deduplication. Several consumers can share the inventory, and multiple layouts or devices for one rotation step can coexist. The application keeps the members within the intended parameter context and secret relation.
The provisioning helper returns the supplied inventory. It reuses compatible existing groups and creates missing keys, considering additional storage across the composition's consumers. A broader key can serve several stages; generating a separate compact key for every depth can require more total storage. Consumer selection checks actual digit supports, QP rows, ring dimension, dtype and device, including the compatibility of an entire hoisted rotation group.
The default rotation-key strategy is all_required. The available strategies are:
| Strategy | Rotation material |
|---|---|
signed_power_of_two | Signed-power keys used through composed rotations |
signed_power_of_two_with_baby_steps | Signed-power coverage plus direct baby steps for the selected BSGS partitions |
all_required | Direct keys for every required logical transform rotation |
Inspect bootstrap.key_steps(strategy) and bootstrap.evaluation_key_requirements(strategy) before generation. Key coverage and baby-rotation hoisting are separate choices. Encapsulation's low and return hints belong to the raising component; rotation, relinearization and conjugation keys in evaluation_keys use the main secret. Generate or load these values before preparation or capture.
3. Refresh and verify a ciphertext
An application supplies a ciphertext at bootstrap.input_depth. For a standalone numerical check, encrypt directly at that depth and the configured input scale:
values = torch.linspace(-0.05, 0.05, engine.num_slots, dtype=torch.float64)
ciphertext = engine.encrypt_message(
values,
public_key,
depth=bootstrap.input_depth,
scale=bootstrap.input_scale,
)
refreshed = bootstrap(ciphertext, evaluation_keys=evaluation_keys)
decoded = engine.decrypt_message(refreshed, secret_key, is_real=True)
error = (decoded - values).abs()
print("entry depth:", bootstrap.input_depth)
print("output depth:", refreshed.depth)
print("remaining depth:", bootstrap.remaining_depth)
print("refresh window:", bootstrap.refresh_window)
print("output actual scale:", refreshed.scale)
print("max error:", error.max().item())
print("mean error:", error.mean().item())2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Input and output are two-component coefficient-domain, standard-residue Q ciphertexts with axes [component, *batch, limb, coefficient]. The output records its active prime_ids and actual scale. Online evaluation uses ciphertexts, evaluation keys and numerical materials; the secret key is used here only to verify the result.
Let the terminal depth be remaining_depth is refresh_window is
For preceding-group entry, integer multiplication and rescale produce an actual source scale input_scale finish compensates the output scale by
The raw reduction coordinate reference(values) consumes normalized coordinates, with target
4. Prepare Eager and compiled execution
Prepare the complete refresh once. Material discovery uses the example's state and device to select key references and encode diagonals and constants, recording the results in ordinary dictionaries. The returned PreparedBootstrap includes entry, normalized core and output scale compensation. It retains the selected references and releases the example payload and temporary result. New encodings consume the rounding RNG once; repeated execution and callable capture reuse those samples.
from fhelium import compile as fc
from fhelium.runtime import CudaGraphProgram
prepared = bootstrap.prepare(ciphertext, evaluation_keys=evaluation_keys)
refreshed_eager = prepared(ciphertext)
optimized = fc.compile(prepared)
refreshed_compiled = optimized(ciphertext)
graph = CudaGraphProgram.capture(
optimized, example_inputs=(ciphertext,), warmup=1
)
try:
refreshed = graph.replay(ciphertext, copy_output=True, synchronize=True)
finally:
graph.close()
prepared.close()2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Eager and Compile use the same prepared Python computation. Compile represents it as ordinary CKKS, RNS, NTT and Tensor operations with live material operands. Adding or removing inventory entries after preparation leaves these bindings unchanged; prepare a new callable to select other keys. In-place writes to selected key Tensors remain visible under the prepared layout and synchronization contract. Compilation consumes existing keys and encoded samples.
copy_output=True returns storage independent of Graph replay. Close a Graph before its prepared owner. A linked compiled executable retains its bound Tensors until that executable is released. Clearing the shared inventory releases only its own references.
The callable can also be source-inlined inside a larger fc.compile function. Select a custom Backend or caller-composed pipeline through the ordinary Compile arguments. For applications that manage normalized coordinates directly, entry, prepare_core and finish remain available; the full prepared callable is the common entry.
5. Choose component and storage policies
FullSlotBootstrap accepts independent Fourier compilers and evaluators, a periodic-reduction component and a modulus-raising component. Use it directly when a named profile does not describe the desired construction. The composition guide shows the constructor and replacement points.
| Choice | Control | Effect |
|---|---|---|
| Raising relation | modulus_raising and its supplied keys | Centered extension or intermediate-secret encapsulation |
| Entry and scale schedule | source_depth, input_depth, input_scale, target_scales | Coordinate conversion, coefficient-product targets and available depth |
| Fourier decomposition | Stage counts and scale_stage on transform compilers | Rotation workload, factor placement and group consumption |
| Polynomial evaluation | Binary, Blocked or Even evaluator | Shared basis, multiplication/relinearization schedule and rounding |
| Giant-step quotient | aggregate or independent | One shared QP quotient or per-giant transitions; different workspace and rounding |
| Weighted products | product_implementation, product_chunk_size | Native or selected generated implementation and expression extent |
| Key inventory | Shared EvaluationKeySet and create_evaluation_keys | Reuse existing groups and provision missing material across the composition |
| Key-switch lift | modup_method | Default exact lift or CRT alternatives requiring a compatible noise budget |
| Material reuse | retain_diagonals, retain_constants | Resident storage versus repeated preparation |
| Diagonal storage | compress_diagonals | Lossless compression of eligible encoded integers |
| Slot semantics | message_domain | Complex branches or generator-five real-slot reconstruction |
Changing a polynomial evaluator preserves the selected coefficients; changing a profile can change the polynomial, Fourier stages and raw bound together. Fixed-weight secrets and auxiliary primes are separate choices from both. No profile automatically searches this design space or chooses a security target for the caller.
6. Performance and material footprint
These measurements were collected on October 31, 2026, on an NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition, with product_implementation="auto" with chunk size 16. The measured 3/30 coefficient-to-slot baby steps are 8192, 512, 32 and 4.
The first five rows use Binary evaluation and independent giant-step quotients. The two Blocked rows and both sparse-secret rows use aggregate quotients. The sparse-secret profile evaluates its even seed through a degree-15 Blocked schedule. Each configuration provisions an initially empty EvaluationKeySet through create_evaluation_keys, allowing full and active-basis keys to share storage across consumers. The final row selects modup_method="normalized_crt"; every other row uses the exact lift.
| Construction | Rotation-key strategy | Remaining depths | Ordinary latency (ms) | Graph latency (ms) | Max absolute error | Keys (GiB) | Diagonals (GiB) | Ordinary peak allocated (GiB) | Ordinary peak reserved (GiB) | Graph peak allocated (GiB) | Graph peak reserved (GiB) |
|---|---|---|---|---|---|---|---|---|---|---|---|
| Centered 7/44 · Binary · int64 | Signed power | 8 | 335.8 | 325.1 | 1.035e-03 | 6.221 | 4.1596 | 11.821 | 12.564 | 11.821 | 12.662 |
| Centered 7/44 · Binary · int64 | Power + babies | 8 | 265.5 | 256.5 | 1.033e-03 | 10.473 | 4.1596 | 16.083 | 16.932 | 16.084 | 16.961 |
| Centered 7/44 · Binary · int64 | All required | 8 | 235.5 | 228.1 | 1.026e-03 | 14.383 | 4.1596 | 20.011 | 20.857 | 20.012 | 20.887 |
| Centered 8/28 · Binary · int64 | Power + babies | 8 | 229.7 | 221.9 | 1.030e-03 | 10.473 | 4.1596 | 16.084 | 16.662 | 16.085 | 16.723 |
| Centered 8/28 · Binary · int64 · three STC stages | Power + babies | 7 | 204.3 | 198.2 | 1.049e-03 | 10.373 | 3.6637 | 15.500 | 16.010 | 15.501 | 16.039 |
| Centered 7/44 · Blocked · int64 | All required | 8 | 161.9 | 156.0 | 1.027e-03 | 15.335 | 4.1596 | 21.010 | 21.355 | 21.005 | 21.922 |
| Centered 7/44 · Blocked · int32 | All required | 8 | 157.0 | 151.2 | 1.013e-03 | 14.427 | 4.1596 | 20.071 | 20.387 | 20.067 | 20.979 |
| Sparse-secret 3/30 · int32 · exact lift | All required | 8 | 67.3 | 64.6 | 8.240e-06 | 6.133 | 0.3905 | 7.410 | 7.699 | 7.410 | 7.740 |
| Sparse-secret 3/30 · int32 · normalized CRT lift | All required | 8 | 62.8 | 60.0 | 8.864e-06 | 6.133 | 0.3905 | 7.411 | 7.701 | 7.411 | 7.742 |
Parameters and depth
The int64 centered configurations use slots32768_scale50_depth27_int64 with generator five: 28 Q primes in single-prime depth groups, four P primes and seven key digits. The int32 centered configuration uses 56 Q primes in two-prime groups, eight P primes and seven key digits. Both centered configurations use input scale
The sparse-secret configuration uses the example's 51 Q primes, 11 main P primes and five key digits, plus the low and return hints. Its intermediate secret has weight 32; the main secret shared by all cases has weight
Every measured callable sets input_depth=engine.max_depth, so entry starts directly from its source Q basis. The table's refresh windows therefore equal the remaining-depth counts. The introductory centered example instead uses the default preceding-group entry, which consumes an additional transition before the normalized core.
Timing and memory scope
Measurements were taken on October 31, 2026, using an AMD Ryzen Threadripper PRO 9965WX, PyTorch 2.13, CUDA 13.0 and driver 580.196.07. PyTorch retained 24 intra-op and 24 inter-op threads. Each configuration ran in three fresh processes, with three warm-ups and twenty timed samples per execution mode. Ordinary execution preceded Graph capture. All cases used radix2_compact_group8_smem8 with Montgomery twiddle tables. The table reports the median of the three process medians; the complete study contains 27 processes and 1080 timed samples.
Both modes execute the same prepared Eager entry/core/finish callable on a fixed resident input. Ordinary latency measures the call followed by synchronization; Graph latency measures replay followed by synchronization. Key generation, material preparation, input copying and Graph capture are outside the timed interval. The first output was checked against the configured output depth, Q rows, shape, representation and entry/core/finish scale equations. Repeated ordinary output, warmed Graph output and the final output after each timing series matched that result exactly. Inputs were checked unchanged after timing. Within each configuration, input, evaluation-key, encoded-material and qualification-output hashes also matched across the three processes. The six int64 centered cases shared the same input ciphertext.
Keys and diagonals are retained Tensor payloads. The complete application inventory remains resident, including keys shared across consumers; encapsulation includes the low and return hints. Each memory column gives the maximum corresponding peak across the three processes. Ordinary peaks come from a separate post-warm-up complete call; Graph peaks cover capture and replay. Allocated memory includes numerical tables, input/output, workspace and resident client verification keys and contexts. Reserved memory additionally includes allocator-held capacity.
Numerical interpretation
On this message, the centered configurations have maximum absolute error near
The sparse-secret exact-lift configuration has maximum error
The centered and sparse-secret constructions change the raising relation, source-modulus/scale ratio, Fourier stages, polynomial and key material together. The table reports each complete configuration's speed, precision and storage; its secret distributions and auxiliary relations remain part of the selected security model.
Example sources
Complete runner
r"""Deplete and refresh one full-slot CKKS ciphertext at $\mathtt{logN}=16$.
The measured profile uses 50-bit scale and structural-base primes, generator 5,
and a periodic-reduction raw `input_bound` of 1024. The example message range is
an empirical end-to-end input, not a proof of the encrypted branch bound.
"""
from __future__ import annotations
import argparse
import time
import torch
import fhelium as fh
from fhelium.eager import Engine
from fhelium.runtime import CudaGraphProgram
from fhelium.experimental.bootstrap import (
cosine_bootstrap,
BinaryDecompositionChebyshevEvaluator,
BlockedChebyshevEvaluator,
EncapsulatedModRaise,
)
def deplete_to_bootstrap_input(
engine: Engine,
ciphertext: fh.Ciphertext,
target_depth: int,
) -> fh.Ciphertext:
r"""Consume public Q depths with multiplication by semantic $1$.
Each iteration multiplies a two-component coefficient-domain standard-RNS
Q ciphertext by an unbatched NTT/Montgomery plaintext at scale $\Delta_0$,
then drops the complete leading Q depth group. The output remains coefficient-domain
standard RNS with axes `[component, *batch, limb, coefficient]`, unchanged
batch shape and component count, next-depth `prime_ids`, and actual
scale $\Delta_{\rm out}=\Delta_{\rm in}\Delta_0/M_{\rm drop}$. The
returned ciphertext is functional; the argument's storage is not mutated.
"""
ones = torch.ones(
engine.num_slots,
dtype=torch.float64,
device=torch.get_default_device(),
)
while ciphertext.depth < target_depth:
identity = engine.prepare_plaintext_for_multiplication(
engine.encode(
ones, depth=ciphertext.depth, scale=engine.config.default_scale
)
)
ciphertext = engine.rescale_to_next_depth(
engine.ntt_domain_to_coefficient_domain(
engine.multiply_plaintext(
engine.coefficient_domain_to_ntt_domain(ciphertext),
identity,
)
)
)
return ciphertext
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
execution = parser.add_mutually_exclusive_group()
execution.add_argument(
"--compile",
dest="execution",
action="store_const",
const="compile",
help="compile the complete prepared refresh (default)",
)
execution.add_argument(
"--eager",
dest="execution",
action="store_const",
const="eager",
help="execute the refresh through Eager",
)
execution.add_argument(
"--core-graph",
dest="execution",
action="store_const",
const="core-graph",
help="prepare and capture the normalized core",
)
parser.set_defaults(execution="compile")
parser.add_argument(
"--message-domain", choices=("complex", "real"), default="complex"
)
parser.add_argument(
"--product-implementation",
choices=("native", "auto", "triton"),
default="auto",
)
parser.add_argument("--product-chunk-size", type=int, default=16)
parser.add_argument(
"--profile", choices=("7/44", "8/28", "8/28-s2c3", "3/30"), default=None
)
parser.add_argument(
"--giant-step-reduction",
choices=("aggregate", "independent"),
default=None,
)
parser.add_argument(
"--polynomial-evaluator",
choices=("profile", "binary", "blocked"),
default="profile",
)
parser.add_argument(
"--rotation-key-strategy",
choices=(
"signed_power_of_two",
"signed_power_of_two_with_baby_steps",
"all_required",
),
default="all_required",
)
parser.add_argument(
"--encapsulated",
action="store_true",
help="use the explicit int32 low-basis encapsulation construction",
)
parser.add_argument("--intermediate-secret-weight", type=int, default=32)
parser.add_argument("--no-retain-diagonals", action="store_true")
args = parser.parse_args()
torch.set_default_device("cuda:0")
auxiliary = None
target_scales = None
if args.encapsulated:
from _bootstrap_encapsulation_parameters import parameters
config, auxiliary, target_scales = parameters()
if args.profile not in {None, "3/30"}:
parser.error(
"the encapsulation parameter example uses profile 3/30"
)
profile = "3/30"
else:
config = fh.CkksConfig.parse(
fh.Preset.slots32768_scale50_depth27_int64, galois_generator=5
)
profile = args.profile or "7/44"
engine = Engine(
config,
allow_automatic_key_generation=False,
)
implementation = {
"native": None,
"auto": "auto",
"triton": "triton-montgomery-weighted-sum",
}[args.product_implementation]
polynomial_evaluator = {
"profile": None,
"binary": BinaryDecompositionChebyshevEvaluator(skip_near_zero=1e-15),
"blocked": BlockedChebyshevEvaluator(baby_step=8),
}[args.polynomial_evaluator]
secret_key = engine.create_secret_key(
hamming_weight=config.N // 2 if args.encapsulated else None
)
modulus_raising = None
if auxiliary is not None:
intermediate = engine.create_secret_key(
hamming_weight=args.intermediate_secret_weight
)
low_key, return_key = engine.create_encapsulation_keys(
secret_key, intermediate, **auxiliary
)
modulus_raising = EncapsulatedModRaise(low_key, return_key, **auxiliary)
del intermediate
bootstrap = cosine_bootstrap(
engine,
profile=profile,
modulus_raising=modulus_raising,
input_depth=config.max_depth if args.encapsulated else None,
target_scales=target_scales,
giant_step_reduction=args.giant_step_reduction,
polynomial_evaluator=polynomial_evaluator,
retain_diagonals=not args.no_retain_diagonals,
message_domain=args.message_domain,
product_implementation=implementation,
product_chunk_size=args.product_chunk_size,
)
for stages, evaluator in (
(bootstrap.coeffs_to_slots, bootstrap.coeffs_to_slots_evaluator),
(bootstrap.slots_to_coeffs, bootstrap.slots_to_coeffs_evaluator),
):
for stage in stages:
print(f"{stage.name}: {evaluator.schedule_for(stage)}")
public_key = engine.create_public_key(secret_key)
evaluation_keys = bootstrap.create_evaluation_keys(
secret_key,
rotation_key_strategy=args.rotation_key_strategy,
)
values = torch.linspace(
-0.1,
0.1,
engine.num_slots,
dtype=torch.float64,
)
depleted = (
engine.encrypt_message(
values,
public_key,
depth=bootstrap.input_depth,
scale=bootstrap.input_scale,
)
if args.encapsulated
else deplete_to_bootstrap_input(
engine,
engine.encrypt_message(values, public_key),
bootstrap.input_depth,
)
)
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats(torch.get_default_device())
started = time.perf_counter()
if args.execution == "compile":
from fhelium import compile as fc
prepared = bootstrap.prepare(depleted, evaluation_keys=evaluation_keys)
try:
optimized = fc.compile(prepared)
refreshed = optimized(depleted)
torch.cuda.synchronize()
elapsed = time.perf_counter() - started
print(f"prepared complete Compile seconds: {elapsed:.6f}")
finally:
prepared.close()
elif args.execution == "core-graph":
coordinate, ratio = bootstrap.entry(depleted)
prepared = bootstrap.prepare_core(
coordinate, evaluation_keys=evaluation_keys
)
torch.cuda.synchronize()
print(
f"entry and core preparation seconds: {time.perf_counter() - started:.6f}"
)
print(f"prepared diagonal bytes: {prepared.cached_diagonal_bytes}")
program = None
try:
capture_started = time.perf_counter()
program = CudaGraphProgram.capture(
prepared, example_inputs=(coordinate,), warmup=1
)
torch.cuda.synchronize()
print(
f"core capture seconds: {time.perf_counter() - capture_started:.6f}"
)
started = time.perf_counter()
refreshed = bootstrap.finish(
program.replay(coordinate, copy_output=True, synchronize=True),
ratio,
)
elapsed = time.perf_counter() - started
finally:
if program is not None:
program.close()
prepared.close()
print(f"core replay with input/output copies seconds: {elapsed:.6f}")
else:
refreshed = bootstrap(depleted, evaluation_keys=evaluation_keys)
torch.cuda.synchronize()
if args.execution == "eager":
elapsed = time.perf_counter() - started
decoded = engine.decrypt_message(refreshed, secret_key, is_real=True).cpu()
error = (decoded - values.cpu()).abs()
print(f'input depth: {depleted.depth}')
print(f'output depth: {refreshed.depth}')
print(f'remaining depth: {bootstrap.remaining_depth}')
print(f'refresh window: {bootstrap.refresh_window}')
print(
'pipeline depth: '
f'{bootstrap.output_depth - bootstrap.modulus_raise_target_depth}'
)
print(
f'periodic raw input bound: {bootstrap.modular_reduction.input_bound}'
)
print(f'output actual scale: {refreshed.scale:.6g}')
print(f'rotation keys: {len(evaluation_keys.rotation_keys)}')
if not args.core_graph:
print(f'bootstrap seconds: {elapsed:.3f}')
print(f'max error: {error.max().item():.6g}')
print(f'mean error: {error.mean().item():.6g}')
print(
'peak allocated GPU GiB: '
f'{torch.cuda.max_memory_allocated(torch.get_default_device()) / 2**30:.3f}'
)
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
Sparse-secret encapsulation parameters
"""Prime groups and scale targets for the low-basis encapsulation example.
The main QP satisfies the configured modulus-budget check. The example does
not assign a security level to fixed-weight secrets or the joint evaluation-key
transcript. Source Q has two primes; CTS/reduction/STC consume 33 of 51 Q rows.
"""
import math
from fhelium import CkksConfig
def parameters():
q_groups = (
(254279681, 253493249),
(253100033, 249561089),
(246415361, 245760001),
(245235713, 244973569, 244842497),
(241827841, 240648193),
(239861761, 239337473),
(236716033, 236584961),
(235798529, 234356737),
(232652801, 232390657),
(231473153, 230817793),
(230686721, 230424577),
(228720641, 228458497),
(228065281, 225574913),
(224133121, 224002049),
(223215617,),
(222953473,),
(222167041, 222035969),
(221249537, 220594177),
(219676673, 218628097),
(217317377, 216924161),
(216137729, 215744513),
(215482369, 214171649),
(211812353, 211025921),
(210370561, 209059841),
(207880193, 206307329),
(205651969, 204865537),
)
p_moduli = (
257949697,
258605057,
260571137,
260702209,
261488641,
261881857,
263323649,
263454721,
264634369,
265420801,
268042241,
)
delta = math.prod(q_groups[-1]) / 32
config = CkksConfig(
logN=16,
q_depth_groups=q_groups,
p_moduli=p_moduli,
default_scale=delta,
galois_generator=5,
)
auxiliary = dict(
low_p_moduli=(268042241,),
return_prime=256376833,
return_p_moduli=(265420801, 268042241),
)
scales = [2.0**55] * (config.max_depth + 1)
for depth in reversed(range(5, 14)):
scales[depth] = math.sqrt(
config.rescale_divisor(depth) * scales[depth + 1]
)
scales[17] = delta
return config, auxiliary, tuple(scales)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