File size: 10,105 Bytes
9e00302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
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
"""
utils/benchmark.py
SecureLens β€” Performance Benchmarking
Measures encryption time, inference time, decryption time.
Run: python utils/benchmark.py
"""

import os, sys, time, json
import numpy as np

sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

from crypto_layer.ckks_engine import CKKSEngine
from cloud_server.encrypted_inference.he_inference import HEInferenceEngine

MODELS_DIR = os.path.join(
    os.path.dirname(__file__), "..", "cloud_server", "models")
RESULTS_DIR = os.path.join(
    os.path.dirname(__file__), "..", "docs")
os.makedirs(RESULTS_DIR, exist_ok=True)

N_RUNS = 10   # number of benchmark runs for averaging


def benchmark_ckks(engine, n_runs=N_RUNS):
    """Benchmarks encrypt, multiply, decrypt operations."""
    print(f"\n[Benchmark] CKKS Operations ({n_runs} runs each)")
    np.random.seed(42)
    vector = np.random.rand(512).tolist()

    # Encryption
    enc_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        enc = engine.encrypt_vector(vector)
        enc_times.append(time.perf_counter() - t)

    # Scalar multiply
    mul_times = []
    enc = engine.encrypt_vector(vector)
    for _ in range(n_runs):
        t = time.perf_counter()
        _ = enc * 0.5
        mul_times.append(time.perf_counter() - t)

    # Decryption
    dec_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        _ = engine.decrypt_vector(enc)
        dec_times.append(time.perf_counter() - t)

    # Serialization
    ser_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        blob = engine.serialize_ciphertext(enc)
        ser_times.append(time.perf_counter() - t)

    blob = engine.serialize_ciphertext(enc)

    results = {
        "encrypt_ms"    : round(np.mean(enc_times)*1000, 3),
        "multiply_ms"   : round(np.mean(mul_times)*1000, 3),
        "decrypt_ms"    : round(np.mean(dec_times)*1000, 3),
        "serialize_ms"  : round(np.mean(ser_times)*1000, 3),
        "ciphertext_kb" : round(len(blob)/1024, 2),
        "plaintext_kb"  : round(len(vector)*8/1024, 4),
        "overhead_ratio": round(len(blob)/(len(vector)*8), 1),
    }

    print(f"  Encryption time    : {results['encrypt_ms']} ms")
    print(f"  Multiply time      : {results['multiply_ms']} ms")
    print(f"  Decryption time    : {results['decrypt_ms']} ms")
    print(f"  Serialization time : {results['serialize_ms']} ms")
    print(f"  Ciphertext size    : {results['ciphertext_kb']} KB")
    print(f"  Plaintext size     : {results['plaintext_kb']} KB")
    print(f"  Overhead ratio     : {results['overhead_ratio']}x")
    return results


def benchmark_inference(engine, ckks_engine, n_runs=N_RUNS):
    """Benchmarks full HE inference pipeline."""
    print(f"\n[Benchmark] HE Inference ({n_runs} runs)")
    np.random.seed(0)
    features = np.random.rand(512).tolist()

    import tenseal as ts
    enc = ts.ckks_vector(ckks_engine.context, features)

    # Layer 1: 512 β†’ 256
    l1_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        h1 = engine._linear(enc, engine.W1, engine.b1,
                             ckks_engine.context)
        l1_times.append(time.perf_counter() - t)

    # Layer 2: 256 β†’ 2
    l2_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        _ = engine._linear(h1, engine.W2, engine.b2,
                            ckks_engine.context)
        l2_times.append(time.perf_counter() - t)

    # Full pipeline
    full_times = []
    for _ in range(n_runs):
        t = time.perf_counter()
        enc_f = ts.ckks_vector(ckks_engine.context, features)
        out   = engine.infer_head(enc_f, ckks_engine.context)
        _     = ckks_engine.decrypt_prediction(out)
        full_times.append(time.perf_counter() - t)

    # Plaintext baseline
    plain_times = []
    W1 = engine.W1
    b1 = engine.b1
    W2 = engine.W2
    b2 = engine.b2
    f  = np.array(features)
    for _ in range(n_runs):
        t  = time.perf_counter()
        h1 = W1 @ f + b1
        h1 = np.maximum(h1, 0)
        _  = W2 @ h1 + b2
        plain_times.append(time.perf_counter() - t)

    results = {
        "layer1_ms"      : round(np.mean(l1_times)*1000, 3),
        "layer2_ms"      : round(np.mean(l2_times)*1000, 3),
        "full_pipeline_ms": round(np.mean(full_times)*1000, 3),
        "plaintext_ms"   : round(np.mean(plain_times)*1000, 4),
        "overhead_factor": round(
            np.mean(full_times)/max(np.mean(plain_times), 1e-9), 1),
    }

    print(f"  Layer 1 (512β†’256)  : {results['layer1_ms']} ms")
    print(f"  Layer 2 (256β†’2)    : {results['layer2_ms']} ms")
    print(f"  Full pipeline      : {results['full_pipeline_ms']} ms")
    print(f"  Plaintext baseline : {results['plaintext_ms']} ms")
    print(f"  Overhead factor    : {results['overhead_factor']}x")
    return results


def benchmark_memory():
    """Measures memory usage of key objects."""
    print("\n[Benchmark] Memory Usage")
    import sys as _sys

    np.random.seed(42)
    features   = np.random.rand(512)
    plain_size = features.nbytes

    import tenseal as ts
    ctx = ts.context(
        ts.SCHEME_TYPE.CKKS,
        poly_modulus_degree=8192,
        coeff_mod_bit_sizes=[60,40,40,60])
    ctx.generate_galois_keys()
    ctx.generate_relin_keys()
    ctx.global_scale = 2**40

    enc      = ts.ckks_vector(ctx, features.tolist())
    enc_blob = enc.serialize()
    ctx_blob = ctx.serialize(save_secret_key=True)

    results = {
        "plaintext_bytes"   : int(plain_size),
        "ciphertext_bytes"  : int(len(enc_blob)),
        "context_bytes"     : int(len(ctx_blob)),
        "overhead_ratio"    : round(len(enc_blob)/plain_size, 1),
        "plaintext_kb"      : round(plain_size/1024, 3),
        "ciphertext_kb"     : round(len(enc_blob)/1024, 2),
        "context_kb"        : round(len(ctx_blob)/1024, 2),
    }

    print(f"  Plaintext  : {results['plaintext_kb']} KB")
    print(f"  Ciphertext : {results['ciphertext_kb']} KB "
          f"({results['overhead_ratio']}x overhead)")
    print(f"  Context    : {results['context_kb']} KB")
    return results


def benchmark_accuracy(engine, ckks_engine):
    """Verifies FHE produces same result as plaintext."""
    print("\n[Benchmark] Accuracy / Correctness Verification")
    np.random.seed(123)
    n_tests = 100
    errors  = []
    matches = 0

    for i in range(n_tests):
        feat = np.random.randn(512) * 0.5

        # Plaintext
        h1p    = engine.W1 @ feat + engine.b1
        h1p    = np.maximum(h1p, 0)
        out_p  = engine.W2 @ h1p + engine.b2
        pred_p = "Normal" if out_p[0] > out_p[1] else "Pneumonia"

        # FHE
        import tenseal as ts
        enc     = ts.ckks_vector(ckks_engine.context, feat.tolist())
        enc_out = engine.infer_head(enc, ckks_engine.context)
        result  = ckks_engine.decrypt_prediction(enc_out)
        pred_f  = result["prediction"]

        decrypted = np.array(enc_out.decrypt()[:2])
        error     = np.max(np.abs(decrypted - out_p[:2]))
        errors.append(error)
        if pred_p == pred_f:
            matches += 1

    results = {
        "n_tests"         : n_tests,
        "prediction_match": matches,
        "match_rate_pct"  : round(matches/n_tests*100, 1),
        "mean_error"      : float(f"{np.mean(errors):.2e}"),
        "max_error"       : float(f"{np.max(errors):.2e}"),
        "min_error"       : float(f"{np.min(errors):.2e}"),
    }

    print(f"  Tests run       : {n_tests}")
    print(f"  Prediction match: {matches}/{n_tests} "
          f"({results['match_rate_pct']}%)")
    print(f"  Mean CKKS error : {results['mean_error']}")
    print(f"  Max  CKKS error : {results['max_error']}")
    return results


def main():
    print("="*55)
    print("  SecureLens β€” Performance Benchmark Suite")
    print("="*55)

    print("\n[Init] Loading CKKS Engine...")
    ckks_engine = CKKSEngine(
        poly_modulus_degree=8192,
        coeff_mod_bit_sizes=[60,40,40,60],
        global_scale=2**40)

    print("[Init] Loading HE Inference Engine...")
    he_engine = HEInferenceEngine(MODELS_DIR)

    # Run all benchmarks
    ckks_results     = benchmark_ckks(ckks_engine)
    infer_results    = benchmark_inference(he_engine, ckks_engine)
    memory_results   = benchmark_memory()
    accuracy_results = benchmark_accuracy(he_engine, ckks_engine)

    # Combine all results
    all_results = {
        "model"     : "SecureLensNet (ResNet-18 + Linear HE Head)",
        "dataset"   : "Chest X-Ray (Kaggle) β€” 5856 images",
        "test_acc"  : "89.42%",
        "ckks_params": {
            "scheme"             : "CKKS",
            "library"            : "TenSEAL 0.3.14",
            "poly_modulus_degree": 8192,
            "coeff_mod_bit_sizes": [60,40,40,60],
            "global_scale"       : "2^40",
            "security_bits"      : 128,
        },
        "ckks_operations" : ckks_results,
        "inference"       : infer_results,
        "memory"          : memory_results,
        "accuracy"        : accuracy_results,
    }

    # Save results
    out_path = os.path.join(RESULTS_DIR, "benchmark_results.json")
    with open(out_path, "w") as f:
        json.dump(all_results, f, indent=2)
    print(f"\n[Saved] Results β†’ {out_path}")

    # Print summary
    print("\n" + "="*55)
    print("  BENCHMARK SUMMARY")
    print("="*55)
    print(f"  Encryption time      : {ckks_results['encrypt_ms']} ms")
    print(f"  Inference time (FHE) : "
          f"{infer_results['full_pipeline_ms']} ms")
    print(f"  Decryption time      : {ckks_results['decrypt_ms']} ms")
    print(f"  Total latency        : "
          f"{ckks_results['encrypt_ms'] + infer_results['full_pipeline_ms'] + ckks_results['decrypt_ms']:.1f} ms")
    print(f"  Ciphertext size      : {ckks_results['ciphertext_kb']} KB")
    print(f"  Prediction match rate: "
          f"{accuracy_results['match_rate_pct']}%")
    print(f"  Max CKKS error       : {accuracy_results['max_error']}")
    print("\nβœ… Benchmark complete.")


if __name__ == "__main__":
    main()