Compiled CUDA Graphs
Example source: examples/17_runtime_cuda_graph.py
A compiled callable on CUDA executes its specialization's exec schedule through a Runner, and with Graphs enabled the Runner captures the schedule's capture-safe segments as CUDA Graphs and replays them. Example 17 compiles two functions that form a pipeline, a packed matrix-vector product graph settings, segment statistics, in-place reads between compiled functions, and the storage of results the caller keeps.
Run the example
python examples/17_runtime_cuda_graph.py
python examples/17_runtime_cuda_graph.py --size 16 --runs 1002
The example requires CUDA and uses slots8192-scale40-depth7. It prints the latency and segment choices of each graph setting, then the pipeline's error, Graph variants, staged copies, and compiled execution memory, and finally the result-ownership counters.
The two functions
def matvec(x):
rotated = Ciphertext.stack_batch([x, *engine.rotate_many_by_steps(x, steps)])
products = engine.sum_plaintext_products(
engine.coefficient_domain_to_ntt_domain(rotated), diagonals)
return engine.rescale_to_next_depth(engine.ntt_domain_to_coefficient_domain(products))
def square(y):
ntt = engine.coefficient_domain_to_ntt_domain(y)
return engine.relinearize(engine.multiply(ntt, ntt), relinearization_key, rescale=True)2
3
4
5
6
7
8
9
matvec evaluates square multiplies, relinearizes, and rescales. The pipeline moves the input from depth 0 to depth 2.
Graph settings
for graph in ("auto", True, False):
first = fc.compile(matvec, graph=graph)
second = fc.compile(square, graph=graph)
second(first(x))2
3
4
The first execution of a specialization runs its schedule directly, the second captures each Graph segment, and later executions replay it. A segment is a maximal run of capture-safe instructions at the top level of the schedule; kernel launches, copies, views, and operator calls on one CUDA device are capture-safe, while Python calls and CPU operations end a segment. With "auto", each segment compares the device time of its first execution with the median of three replays after capture and keeps its Graph only when replay is faster; True keeps every Graph, and False runs every call directly. Each record in compiled.stats()["graphs"] lists its segments with choice equal to "graph", "direct", or "measuring" before the decision. For this small pipeline both segments keep their Graphs under "auto", and replay reduces latency relative to graph=False.
Reading a predecessor's output in place
Compiled functions on one device share one arena for their temporaries and the Graph pool of their Runners. The output of first lies in its Runner's output region, and second reads it there: a segment that reads another Runner's storage keeps up to four captured variants, one for each set of input addresses, instead of copying its inputs into its own storage. The example reports one captured variant and no staged input copies for the activation. fhelium.backend.runner.compiled_execution_bytes(device) reports the device memory that the shared arena and the Graph pool hold.
Results the caller keeps
A Graph result is returned in the Runner's output region without a copy. When the caller still references a result and the next execution would overwrite that region, the Runner first moves the result to separate storage, so every result stays valid while the caller holds it. The example keeps three results in a list and finds three distinct storages, with the moves counted as detached_outputs in the Graph statistics; when the loop instead drops each result with del before the next call, no further moves occur apart from the one result still referenced when the loop starts. Keeping results is correct and costs one device copy per kept result.
Clear the callables
clear() releases the specializations, their Graphs, and their Runners. Call it after the last result has been consumed.
Use CUDA Graphs covers the graph option for an existing function and the manual CudaGraphProgram capture of Eager code. Compiled execution defines schedules, storage classes, and segments.
Source
#!/usr/bin/env python3
"""Run compiled CKKS functions through CUDA Graph segments.
Two compiled functions form a pipeline: a packed matrix-vector product ``A x`` with the cyclic-diagonal method and a square activation. For each ``graph`` setting the example reports latency and the execution choice of each Graph segment. It then shows that the activation reads the product's output in place, and that a result the caller keeps across calls is moved to separate storage before the next call overwrites it.
"""
from __future__ import annotations
import argparse
import torch
from common import print_table, time_ms
import fhelium as fh
from fhelium import compile as fc
from fhelium.backend.runner import compiled_execution_bytes
from fhelium.eager import Engine
from fhelium.values import Ciphertext, Plaintext
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--device", default="cuda:0")
parser.add_argument("--size", type=int, default=8)
parser.add_argument("--runs", type=int, default=50)
args = parser.parse_args()
device = torch.device(args.device)
if device.type != "cuda":
parser.error("CUDA Graph segments require a CUDA device")
config = fh.CkksConfig.parse(fh.Preset.slots8192_scale40_depth7)
engine = Engine(config, rng_seed=17)
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
steps = tuple(-k for k in range(1, size))
engine.keys.update(
engine.create_rotation_key(step, secret_key, device=device)
for step in steps
)
row = torch.arange(size, dtype=torch.float64).view(-1, 1)
column = torch.arange(size, dtype=torch.float64).view(1, -1)
matrix = 0.3 * torch.sin((row + 1) * (column + 2) * 0.17)
slots = torch.arange(engine.num_slots) % size
diagonals = Plaintext.stack_batch(
[
engine.prepare_plaintext_for_multiplication(
engine.encode(matrix[slots, (slots + k) % size], device=device)
)
for k in range(size)
]
)
def matvec(x: Ciphertext) -> Ciphertext:
rotated = Ciphertext.stack_batch(
[x, *engine.rotate_many_by_steps(x, steps)]
)
products = engine.sum_plaintext_products(
engine.coefficient_domain_to_ntt_domain(rotated), diagonals
)
return engine.rescale_to_next_depth(
engine.ntt_domain_to_coefficient_domain(products)
)
def square(y: Ciphertext) -> Ciphertext:
ntt = engine.coefficient_domain_to_ntt_domain(y)
return engine.relinearize(
engine.multiply(ntt, ntt), relinearization_key, rescale=True
)
generator = torch.Generator().manual_seed(17)
vectors = [
0.5 * torch.rand(size, generator=generator, dtype=torch.float64)
for _ in range(3)
]
inputs = [
engine.encrypt_message(
v.repeat(engine.num_slots // size), public_key, device=device
)
for v in vectors
]
# Latency and segment choices for each graph setting.
rows = []
for graph in ("auto", True, False):
first = fc.compile(matvec, graph=graph)
second = fc.compile(square, graph=graph)
timing, _ = time_ms(
lambda: second(first(inputs[0])),
warmup=3,
runs=args.runs,
device=device,
)
choices = [
[segment["choice"] for segment in record["segments"]]
for compiled in (first, second)
for record in compiled.stats()["graphs"]
]
rows.append([str(graph), f"{timing['mean_ms']:.3f}", choices])
first.clear()
second.clear()
print_table(["graph", "mean ms", "segment choices (matvec, square)"], rows)
# A pipeline of two compiled functions on one device.
first = fc.compile(matvec, graph=True)
second = fc.compile(square, graph=True)
errors = []
for vector, x in zip(vectors, inputs * 2, strict=False):
result = second(first(x))
decoded = engine.decrypt_message(result, secret_key, is_real=True)
errors.append(
float((decoded[:size].cpu() - (matrix @ vector) ** 2).abs().max())
)
del result
for _ in range(3):
result = second(first(inputs[0]))
del result
capture = second.stats()["graphs"][0]["capture_stats"]
print()
print_table(
["activation reading the product in place", "value"],
[
["max abs error over inputs", f"{max(errors):.3e}"],
["captured variants", capture["variants"]],
["staged input copies", capture["staged_copies"]],
[
"compiled execution bytes on the device",
compiled_execution_bytes(device.index or 0),
],
],
)
# Results the caller keeps are moved out of the output region.
kept = [second(first(x)) for x in inputs]
dropped_before = second.stats()["graphs"][0]["capture_stats"][
"detached_outputs"
]
for x in inputs:
output = second(first(x))
del output
dropped_after = second.stats()["graphs"][0]["capture_stats"][
"detached_outputs"
]
distinct = len({result.data.data_ptr() for result in kept})
print()
print_table(
["result ownership", "value"],
[
[
"kept results with distinct storage",
f"{distinct} of {len(kept)}",
],
["detached outputs while keeping results", dropped_before],
[
"additional detaches after dropping",
dropped_after - dropped_before,
],
],
)
del kept
first.clear()
second.clear()
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