Depth and scale
Example source: examples/03_eager_depth_and_scale.py
This example prints the modulus chain of one preset, the active Q basis, default scale, and rescale ratio of selected depths, and then plans the scales of two plaintext products so that the rescaled result can be added to a second branch aligned by a modulus switch. It closes with a power-of-two scale allocation and a bounded scale reinterpretation.
Run the example
python examples/03_eager_depth_and_scale.py --preset slots8192-scale40-depth7Select the depths of the chain table:
python examples/03_eager_depth_and_scale.py \
--preset slots32768-scale40-depth34 \
--depths 0,16,332
3
1. Each depth selects a set of Q primes
A resolved configuration stores
config.q_moduli # ordered Q primes q_0 ... q_{L-1}
config.q_bases # prime IDs of the active Q basis B_d at every depth
config.max_depth # D = len(q_bases) - 12
3
config.q_prime_ids(d) lists the prime IDs of config.active_q_moduli(d) their values. Values use depths from zero through Q rows and log2 B_d columns report remaining reports config.depth_remaining(d).
2. A rescale drops and introduces primes
A rescale from depth
The |D|/|R| column reports the numbers of dropped and introduced primes from config.basis_transition(d, d + 1), and log2 rho_d reports config.rescale_divisor(d). The built-in presets combine primes near
config.scale_at(d) is the scale used when a value is created at depth scale argument; the log2 scale column lists it. The maximum-depth entry equals the preset scale, and earlier entries satisfy
The CT size column shows that a depth-0 ciphertext is the largest. A two-component ciphertext stores approximately int32 for every built-in preset.
3. Plan two plaintext products against the actual ratio
Every value owns its actual binary64 scale. Two plaintext products multiply it without consuming a depth, and one rescale divides by
The example reads
rescale_ratio = engine.rescale_divisor(depth=source.depth)
first_scale = float(1 << (math.floor(math.log2(target_scale)) // 2))
second_scale = target_scale * float(rescale_ratio) / (source.scale * first_scale)2
3
engine.rescale_output_scale(pre_rescale_scale, depth=d) computes the recorded scale after one rescale without residue arithmetic; the example prints it beside the target.
4. Align depth independently from scale
The second branch stays at depth zero until a modulus switch moves it to depth one:
depth_aligned_source = engine.mod_switch_to_depth(source, source.depth + 1)
target_scale = depth_aligned_source.scale2
When config.scale_at(1). The example uses the switched scale as the target of the planned product, so the two branches have the same depth and the same binary64 scale, and engine.add(planned, depth_aligned_source) receives compatible operands.
5. Reinterpret a mismatched scale within a bound
Replacing
reinterpreted = engine.reinterpret_at_scale(
approximate, target_scale, max_relative_change=args.reinterpret_bound
)2
3
The decoded message is multiplied by old_scale / target_scale, and the bound limits the accepted ratio. The final table compares each decoded result with the corresponding cleartext expression.
Source
#!/usr/bin/env python3
"""Inspect the modulus chain of a preset, then plan and track per-value CKKS scales.
The first table lists the active Q basis, default scale, and rescale ratio of
selected depths. The second part allocates the scales of two plaintext factors
so that their product, after one rescale, reaches a target scale; aligns a
second branch by depth with a modulus switch; and compares the result with a
power-of-two allocation followed by a bounded scale reinterpretation.
Run:
python examples/03_eager_depth_and_scale.py --preset slots8192-scale40-depth7
"""
from __future__ import annotations
import argparse
import math
import torch
from common import (
add_engine_args,
error_stats,
format_bytes,
make_engine,
print_table,
sync_if_cuda,
)
import fhelium as fh
from fhelium.eager import Engine
def chain_rows(
engine: Engine, depths: list[int], device: torch.device
) -> list[list[object]]:
"""Return one display row per depth of the engine's modulus chain."""
config = engine.config
rows = []
for depth in depths:
if depth < config.max_depth:
dropped, introduced = config.basis_transition(depth, depth + 1)
ratio = f"{math.log2(config.rescale_divisor(depth)):.2f}"
else:
dropped, introduced, ratio = (), (), "-"
ciphertext = engine.encrypt_message(
[1, 2, 3, 4], depth=depth, device=device
)
rows.append(
[
depth,
config.depth_remaining(depth),
len(config.q_prime_ids(depth)),
f"{math.log2(math.prod(config.active_q_moduli(depth))):.1f}",
f"{math.log2(config.scale_at(depth)):.2f}",
f"{len(dropped)}/{len(introduced)}",
ratio,
format_bytes(ciphertext.data.nbytes),
]
)
return rows
def multiply_twice_then_rescale(
engine: Engine,
source: fh.Ciphertext,
first_message: torch.Tensor,
second_message: torch.Tensor,
*,
first_scale: float,
second_scale: float,
) -> tuple[fh.Ciphertext, fh.Ciphertext, fh.Ciphertext]:
r"""Apply two plaintext products at the given scales, then one rescale.
The actual-scale path is
$$
\Delta(c_1)=\Delta(c_0)\Delta(p_1),\qquad
\Delta(c_2)=\Delta(c_1)\Delta(p_2),\qquad
\Delta(c_3)=\frac{\Delta(c_2)}{\rho_d},
\qquad \rho_d=\frac{\prod_{q\in D_d}q}{\prod_{q\in R_d}q}.
$$
Decoded slots satisfy $m_3\approx m_0m_1m_2$ up to CKKS approximation
error. The two products keep depth $d$; the rescale moves to $d+1$.
Returns:
Ciphertexts after the first product, second product, and rescale.
"""
first = engine.prepare_plaintext_for_multiplication(
engine.encode(first_message, depth=source.depth, scale=first_scale)
)
second = engine.prepare_plaintext_for_multiplication(
engine.encode(second_message, depth=source.depth, scale=second_scale)
)
after_first = engine.multiply_plaintext(
engine.coefficient_domain_to_ntt_domain(source), first
)
before_rescale = engine.multiply_plaintext(after_first, second)
return (
after_first,
before_rescale,
engine.rescale_to_next_depth(
engine.ntt_domain_to_coefficient_domain(before_rescale)
),
)
def scale_row(label: str, value: fh.Ciphertext) -> list[object]:
"""Return one display row for a ciphertext's depth and recorded scale."""
return [
label,
value.depth,
f"{value.scale:.17g}",
f"{math.log2(value.scale):.9f}",
]
def error_row(
label: str, engine: Engine, value: fh.Ciphertext, expected: torch.Tensor
) -> list[object]:
"""Decrypt one result and return its approximation error."""
error = error_stats(
engine.decrypt_message(value).cpu(), expected, engine.num_slots
)
return [label, f"{error['max_abs']:.3e}", f"{error['rms']:.3e}"]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_engine_args(parser, default_preset="slots8192-scale40-depth7")
parser.add_argument(
"--depths",
default=None,
help="Comma-separated depths for the chain table. Default: first, middle, and last depths.",
)
parser.add_argument(
"--reinterpret-bound",
type=float,
default=5e-2,
help="Maximum symmetric relative scale change accepted by the reinterpretation.",
)
args = parser.parse_args()
engine = make_engine(args)
device = torch.device(args.device)
config = engine.config
# Part 1: the modulus chain. Each depth selects a set of Q primes; a
# rescale from depth d drops D_d, introduces R_d, and divides by rho_d.
depths = (
[int(item) for item in args.depths.split(",")]
if args.depths
else sorted(
{
0,
1,
config.max_depth // 2,
config.max_depth - 1,
config.max_depth,
}
)
)
print(
f"Preset {args.preset}: max depth {config.max_depth}, "
f"{config.num_q_primes} Q and {config.num_p_primes} P primes, "
f"log2(QP)={config.total_modulus_bits} of "
f"{config.maximum_modulus_bits} security budget bits, "
f"RNS dtype {str(engine.dtype).removeprefix('torch.')}."
)
print_table(
[
"depth",
"remaining",
"Q rows",
"log2 B_d",
"log2 scale",
"|D|/|R|",
"log2 rho_d",
"CT size",
],
chain_rows(engine, depths, device),
)
# Part 2: per-value scales.
slots = engine.num_slots
message = 0.01 * torch.sin(
torch.arange(slots, dtype=torch.float64, device=device) * 0.013
)
first_message = torch.linspace(
0.8, 1.2, slots, dtype=torch.float64, device=device
)
second_message = torch.linspace(
1.1, 0.9, slots, dtype=torch.float64, device=device
)
expected_product = message * first_message * second_message
source = engine.encrypt_message(message)
rescale_ratio = engine.rescale_divisor(depth=source.depth)
# Depth alignment is independent of scale alignment: the second branch
# reaches the next depth by a modulus switch, and the planned product
# targets the scale that switch produces.
depth_aligned_source = engine.mod_switch_to_depth(source, source.depth + 1)
target_scale = depth_aligned_source.scale
# The first factor receives a precision allocation; the second completes
# the product that reaches the target after division by rho_0.
first_scale = float(1 << (math.floor(math.log2(target_scale)) // 2))
second_scale = (
target_scale * float(rescale_ratio) / (source.scale * first_scale)
)
planned_first, planned_pre, planned = multiply_twice_then_rescale(
engine,
source,
first_message,
second_message,
first_scale=first_scale,
second_scale=second_scale,
)
predicted_scale = engine.rescale_output_scale(
planned_pre.scale, depth=planned_pre.depth
)
planned_sum = engine.add(planned, depth_aligned_source)
# The comparison allocation replaces rho_0 by the nearest power of two.
# Rescale divides by the actual rho_0, so this result's scale differs
# from the target and the branches cannot be added directly.
nominal_ratio = 2.0 ** round(math.log2(rescale_ratio))
approximate_second_scale = (
target_scale * nominal_ratio / (source.scale * first_scale)
)
_, approximate_pre, approximate = multiply_twice_then_rescale(
engine,
source,
first_message,
second_message,
first_scale=first_scale,
second_scale=approximate_second_scale,
)
# Reinterpretation records the target scale and keeps the residues; the
# bound limits the accepted change of the decoded message.
reinterpreted = engine.reinterpret_at_scale(
approximate, target_scale, max_relative_change=args.reinterpret_bound
)
reinterpreted_sum = engine.add(reinterpreted, depth_aligned_source)
sync_if_cuda(device)
print(
f"\ndepth-{source.depth} rescale ratio log2: {math.log2(rescale_ratio):.6f}"
)
print(f"target scale at depth {planned.depth}: {target_scale:.17g}")
print(f"predicted scale after rescale: {predicted_scale:.17g}")
print(f"plaintext scales: p1={first_scale:.17g}, p2={second_scale:.17g}")
print("\nScale states")
print_table(
["value", "depth", "scale", "log2(scale)"],
[
scale_row("source", source),
scale_row("planned after product 1", planned_first),
scale_row("planned before rescale", planned_pre),
scale_row("planned after rescale", planned),
scale_row("depth-switched source", depth_aligned_source),
scale_row("power-of-two before rescale", approximate_pre),
scale_row("power-of-two after rescale", approximate),
scale_row("reinterpreted", reinterpreted),
],
)
print(
"\nRelative scale difference of the power-of-two result: "
f"{approximate.scale / target_scale - 1.0:.9e}"
)
# Reinterpretation multiplies the decoded product by old_scale/new_scale.
reinterpret_ratio = approximate.scale / reinterpreted.scale
print("\nDecoded error")
print_table(
["result", "max abs error", "rms error"],
[
error_row("planned product", engine, planned, expected_product),
error_row(
"power-of-two product", engine, approximate, expected_product
),
error_row(
"planned product + depth-switched source",
engine,
planned_sum,
expected_product + message,
),
error_row(
"reinterpreted product + source",
engine,
reinterpreted_sum,
expected_product * reinterpret_ratio + message,
),
],
)
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
299
300
301
302
303
304
305
306
Next step
Continue with Late relinearization and NTT reuse. The chain is defined in Configuration and modulus chain, and the scale and depth effects of every operation in Evaluator operation transitions. Choose a preset and chain depth applies them to parameter selection.