-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathattack_testing.py
More file actions
2134 lines (1916 loc) · 74.6 KB
/
attack_testing.py
File metadata and controls
2134 lines (1916 loc) · 74.6 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
from lwe import CreateLWEInstance
from instances import (
BaiGalCenteredScaledTernary,
BaiGalModuleLWE,
estimate_target_upper_bound_ternary_vec,
estimate_target_upper_bound_binomial_vec,
)
from functools import cache
import psutil
import os
import numpy as np
import time
import csv
import traceback
import matplotlib.pyplot as plt
import cupy as cp
from blaster import reduce
from blaster import get_profile, slope, rhf
from estimator import LWE, ND
from fpylll.util import gaussian_heuristic
# Remainder : install prerelease cupy 14.0.* with pip for having solve_triangular batched
from cupyx.scipy.linalg import solve_triangular
from fpylll import IntegerMatrix, GSO, CVP, FPLLL
import hashlib
from itertools import combinations, product
from itertools import islice
from tqdm import tqdm
def _basis_cache_path(beta, target, savedir="saved_basis", literal_target=False):
os.makedirs(savedir, exist_ok=True)
if literal_target:
t_str = ",".join(map(str, np.asarray(target, dtype=np.int64).tolist()))
else:
# nom court et stable: BLAKE2s des octets de target
t_bytes = np.asarray(target, dtype=np.int64).tobytes()
t_str = hashlib.blake2s(t_bytes, digest_size=12).hexdigest()
return os.path.join(savedir, f"{beta}_{t_str}.npy")
def _atomic_save_npy(path, arr):
np.save(path, arr)
def reduction(
basis,
beta,
eta,
target,
target_estimation,
svp=False,
cache_dir="saved_basis",
literal_target_name=False,
):
timestart = time.time()
basis = np.array(basis, dtype=np.int64)
B_np = basis.T
final_beta = beta
print(f"try a progressive BKZ-{beta} on a {basis.shape} matrix")
target_norm = np.linalg.norm(target)
print("target", target)
print("target norm", target_norm)
print("target estimation", np.linalg.norm(target_estimation))
bkz_prog = 10
tours_final = 1
# progressive schedule
list_beta = [30] + list(range(40 + ((beta - 40) % bkz_prog), beta + 1, bkz_prog))
for i, beta in enumerate(list_beta):
# ---------- CHECKPOINT: charge si dispo ----------
ckpt_path = _basis_cache_path(beta, target, cache_dir, literal_target_name)
if os.path.exists(ckpt_path):
try:
B_np = np.load(ckpt_path, allow_pickle=False)
print(f"[cache] loaded basis for β={beta} from {ckpt_path}")
prof = get_profile(B_np)
print("Slope:", slope(prof), f" (rhf={rhf(prof)})")
continue # on saute le calcul pour ce β
except Exception as e:
print(f"[cache] failed to load {ckpt_path}: {e} — recompute…")
# ---------- CALCUL ----------
if beta < 40:
print(f"just do a DeepLLL-{beta}")
_, B_np, _ = reduce(
B_np, use_seysen=True, depth=beta, bkz_tours=1, cores=16, verbose=False
)
elif beta < 60:
print(f"try a BKZ-{beta} on a {basis.shape} matrix")
_, B_np, _ = reduce(
B_np,
use_seysen=True,
beta=beta,
bkz_tours=(tours_final if beta == final_beta else 1),
cores=16,
verbose=False,
)
elif beta <= 80:
print(f"try a BKZ-{beta} like with G6K on a {basis.shape} matrix")
_, B_np, _ = reduce(
B_np,
use_seysen=True,
beta=beta,
bkz_tours=(tours_final if beta == final_beta else 1),
cores=16,
verbose=False,
g6k_use=True,
bkz_size=beta + 20,
jump=21,
)
else:
print(f"try a BKZ-{beta} like with G6K on a {basis.shape} matrix")
_, B_np, _ = reduce(
B_np,
use_seysen=True,
beta=beta,
bkz_tours=(tours_final if beta == final_beta else 1),
cores=16,
verbose=False,
g6k_use=True,
bkz_size=beta + 2,
jump=2,
)
# ---------- CHECKPOINT: sauve après ce β ----------
try:
_atomic_save_npy(ckpt_path, B_np)
print(f"[cache] saved basis for β={beta} to {ckpt_path}")
except Exception as e:
print(f"[cache] failed to save {ckpt_path}: {e}")
# SAVE PROFILE
prof = get_profile(B_np)
print("Slope:", slope(prof), f" (rhf={rhf(prof)})")
# save profile
prof_path = ckpt_path.replace(".npy", "_profile.npy")
try:
_atomic_save_npy(prof_path, prof)
print(f"[cache] saved profile for β={beta} to {prof_path}")
except Exception as e:
print(f"[cache] failed to save {prof_path}: {e}")
# ---------- CHECK IF WE FOUND THE TARGET ----------
if svp: # because if not the basis is not the same dimension as the target
if (B_np[:, 0] == target).all() or (B_np[:, 0] == -target).all():
finish = time.time()
return B_np.T, finish - timestart
# ====== SVP option (inchangé, on ne checkpoint pas ici car tu parlais bien de la boucle β) ======
if svp:
if (B_np[:, 0] == target).all() or (B_np[:, 0] == -target).all():
finish = time.time()
return B_np.T, finish - timestart
prof = get_profile(B_np)
d = basis.shape[0]
rr = [
(2.0 ** prof[i]) ** 2 for i in range(d)
] # norme 2 squared for be the same as get_r fpylll
for n_expected in range(eta, d - 2):
x = np.linalg.norm(target_estimation[d - n_expected :]) ** 2
if 4.0 / 3.0 * gaussian_heuristic(rr[d - n_expected :]) > x:
break
print("n_expected", n_expected)
eta = max(eta, n_expected)
llb = d - eta
while (
gaussian_heuristic([(2.0 ** prof[i]) ** 2 for i in range(llb, d)])
< np.linalg.norm(target_estimation[llb:]) ** 2
): # noqa
llb -= 1
if llb < 0:
break
lift_slack = 5
kappa = max(0, llb - lift_slack)
f = math.floor(11 + (d - kappa) / 15)
# in g6k f = d-kappa-eta (maybe need to edit)
eta = max(eta, d - kappa - f)
print("kappa", kappa)
print(f"try a SVP-{eta} with G6K on a {B_np.shape} matrix")
_, B_np, _ = reduce(
B_np,
use_seysen=True,
beta=eta,
bkz_tours=1,
cores=16,
verbose=False,
svp_call=True,
lifting_start=kappa,
target=np.linalg.norm(target_estimation[kappa:]),
)
if (B_np[:, 0] == target).all() or (B_np[:, 0] == -target).all():
finish = time.time()
return B_np.T, finish - timestart
finish = time.time()
return B_np.T, finish - timestart
def svp(
basis,
eta,
columns_to_keep,
A,
b_vec,
tau,
n,
k,
m,
secret_possible_values,
search_space_dim,
target_estimation,
scaling_factor_y,
):
timestart = time.time()
b = np.array(b_vec.list(), dtype=basis.dtype)
subA = A[:m, :]
dim = basis.shape[0] + 1
removed_cols = [j for j in range(n) if j not in columns_to_keep]
col_vecs = {j: subA[:, j] for j in removed_cols}
# estimate
B_try = np.vstack([basis, b])
_, B_try, _ = reduce(B_try.T, use_seysen=True, depth=4, cores=16, verbose=False)
if np.linalg.norm(B_try[:, 0]) <= np.linalg.norm(target_estimation):
print("find during the LLL")
finish = time.time()
return B_try.T, finish - timestart
prof = get_profile(B_try)
rr = [
(2.0 ** prof[i]) ** 2 for i in range(dim)
] # norme 2 squared for be the same as get_r fpylll
for n_expected in range(eta, dim - 2):
x = np.linalg.norm(target_estimation[dim - n_expected :]) ** 2
if 4.0 / 3.0 * gaussian_heuristic(rr[dim - n_expected :]) > x:
break
print("n_expected", n_expected)
eta = max(eta, n_expected)
llb = dim - eta
while (
gaussian_heuristic([(2.0 ** prof[i]) ** 2 for i in range(llb, dim)])
< np.linalg.norm(target_estimation[llb:]) ** 2
): # noqa
llb -= 1
if llb < 0:
break
lift_slack = 5
kappa = max(0, llb - lift_slack)
f = math.floor(11 + (dim - kappa) / 15)
# in g6k f = d-kappa-eta (maybe need to edit)
eta = max(eta, dim - kappa - f)
print("kappa", kappa)
print(f"try a SVP-{eta} with G6K on a {B_try.shape} matrix")
_, B_try, _ = reduce(
B_try,
use_seysen=True,
beta=eta,
bkz_tours=1,
cores=16,
verbose=False,
svp_call=True,
lifting_start=kappa,
target=np.linalg.norm(target_estimation[kappa:]),
)
if np.linalg.norm(B_try[:, 0]) <= np.linalg.norm(target_estimation):
finish = time.time()
return B_try.T, finish - timestart
for d in range(1, search_space_dim + 1):
total_guesses = math.comb(len(removed_cols), d)
for guess in tqdm(
combinations(removed_cols, d), total=total_guesses, desc=f"Combi ({d})"
):
for value in product(secret_possible_values, repeat=d):
diff = b.copy()
vecs = np.column_stack([col_vecs[j] for j in guess])
diff[n - k : -1] -= vecs.dot(value) * scaling_factor_y
B_try = np.vstack([basis, diff])
_, B_try, _ = reduce(
B_try.T,
use_seysen=True,
beta=eta,
bkz_tours=1,
cores=16,
verbose=False,
svp_call=True,
lifting_start=kappa,
target=np.linalg.norm(target_estimation[kappa:]),
)
if np.linalg.norm(B_try[:, 0]) <= np.linalg.norm(target_estimation):
finish = time.time()
return B_try.T, finish - timestart
# didn't find anything
finish = time.time()
return B_try.T, finish - timestart
def _value_batches(values, d, batch_size):
it = product(values, repeat=d)
while True:
block = list(islice(it, batch_size))
if not block:
break
yield cp.asarray(block, dtype=cp.float64).T
_vals64_src = r"""
extern "C"{
__global__ void gen_values_kernel_f64(const double* __restrict__ vals,
const int L, const int d,
const unsigned long long start_rank,
const int count,
double* __restrict__ out, const int ld)
{
int t = blockDim.x * blockIdx.x + threadIdx.x;
if (t >= count) return;
unsigned long long idx = start_rank + (unsigned long long)t;
// colonne t, lignes 0..d-1 (Fortran: out[t*ld + row])
for (int p = d - 1; p >= 0; --p){
unsigned long long q = idx / (unsigned long long)L;
unsigned int rem = (unsigned int)(idx - q * (unsigned long long)L);
out[(size_t)t * ld + p] = vals[rem];
idx = q;
}
}
}"""
_mod_vals64 = cp.RawModule(code=_vals64_src)
_gen_vals64 = _mod_vals64.get_function("gen_values_kernel_f64")
_src = r"""
extern "C"{
// values-product: enumerate base-L digits -> V (d, B) in Fortran layout
__global__ void gen_values_kernel(const float* __restrict__ vals,
const int L, const int d,
const unsigned long long start_rank,
const int count,
float* __restrict__ out, const int ld)
{
int t = blockDim.x * blockIdx.x + threadIdx.x;
if (t >= count) return;
unsigned long long idx = start_rank + (unsigned long long)t;
// write column t, rows 0..d-1 (Fortran: out[t*ld + row])
// compute most-significant first to match itertools.product order
for (int p = d - 1; p >= 0; --p){
unsigned long long q = idx / (unsigned long long)L;
unsigned int rem = (unsigned int)(idx - q * (unsigned long long)L);
out[(size_t)t * ld + p] = vals[rem];
idx = q;
}
}
__device__ __forceinline__ unsigned long long
C_at(const unsigned long long* __restrict__ choose, int row, int col, int jdim) {
#if __CUDA_ARCH__ >= 350
return __ldg(&choose[(size_t)row * jdim + col]); // read-only cache
#else
return choose[(size_t)row * jdim + col];
#endif
}
// Lexicographic unranking with binary search per coordinate.
// choose shape: (n+1, jdim), row-major: choose[row * jdim + col]
__global__ void unrank_combinations_lex_bs(const unsigned long long* __restrict__ choose,
const int n, const int k,
const unsigned long long start_rank,
const int count,
int* __restrict__ out,
const int jdim)
{
// grid-stride loop: support very large 'count'
for (int t = blockIdx.x * blockDim.x + threadIdx.x; t < count;
t += blockDim.x * gridDim.x)
{
unsigned long long s = start_rank + (unsigned long long)t; // rank for this thread
int a = 0; // minimal value for current coordinate
const int out_base = t * k; // row-major output
// Build combo in increasing order (k entries)
// j goes from k down to 1 (same as ton code)
for (int j = k; j >= 1; --j) {
const int max_x = n - j; // last admissible x (need room for j items)
// T = C(n - a, j), thr = T - s
const int row_na = n - a;
const unsigned long long T = C_at(choose, row_na, j, jdim);
const unsigned long long thr = T - s; // > 0 (s < T automatiquement)
// find the **largest** x in [a, max_x] with C(n - x, j) >= thr
int lo = a, hi = max_x, ans = a; // invariant: ans is last true
while (lo <= hi) {
const int mid = (lo + hi) >> 1;
const unsigned long long c = C_at(choose, n - mid, j, jdim);
if (c >= thr) { ans = mid; lo = mid + 1; }
else { hi = mid - 1; }
}
const int x = ans;
// write output (row-major). Option: column-major for coalesced writes (voir notes)
out[out_base + (k - j)] = x;
// update rank remainder and next lower bound
const unsigned long long c_x = C_at(choose, n - x, j, jdim);
// s <- s - (T - C(n - x, j)) (reste dans [0, C(n - x, j) - 1])
s -= (T - c_x);
a = x + 1;
}
}
}
} // extern "C"
""".strip()
_mod = cp.RawModule(code=_src, options=("-std=c++11",))
_kernel_vals = _mod.get_function("gen_values_kernel")
_kernel_comb = _mod.get_function("unrank_combinations_lex_bs")
_TPB = 256
# ===== helpers =====
def _build_choose_table_dev(n: int, k: int) -> cp.ndarray:
"""
choose_dev[u, j] = C(u, j) for u in [0..n], j in [0..k-1]
(on a besoin de j jusqu'à k-1 pour l'unranking lex)
"""
C = np.zeros((n + 1, k), dtype=np.uint64)
C[:, 0] = 1
for u in range(1, n + 1):
up_to = min(u, k - 1)
for j in range(1, up_to + 1):
C[u, j] = C[u - 1, j] + C[u - 1, j - 1]
return cp.asarray(C) # upload une seule fois
# ===== GPU batchers =====
def value_batches_fp32_gpu(values, d: int, batch_size: int):
"""
Compute on GPU (no H2D overhead for send the batch) blocks V_gpu,
it's equal (but here CPU bounded) to list(islice(product(values, repeat=d), ...)).T
values: 1D array-like
"""
vals_dev = (
values
if isinstance(values, cp.ndarray)
else cp.asarray(values, dtype=cp.float32)
)
L = int(vals_dev.size)
total = L**d
assert total < (1 << 64), "L**d trop grand pour uint64."
start = 0
while start < total:
B = min(batch_size, total - start)
V_gpu = cp.empty((d, B), dtype=cp.float32, order="F")
grid = ((B + _TPB - 1) // _TPB,)
_kernel_vals(
grid,
(_TPB,),
(
vals_dev,
cp.int32(L),
cp.int32(d),
cp.uint64(start),
cp.int32(B),
V_gpu,
cp.int32(d),
),
)
yield V_gpu
start += B
def value_batches_fp64_gpu(values, d: int, batch_size: int):
vals = (
values
if isinstance(values, cp.ndarray)
else cp.asarray(values, dtype=cp.float64)
)
L = int(vals.size)
total = L**d
start = 0
while start < total:
B = min(batch_size, total - start)
V = cp.empty((d, B), dtype=cp.float64, order="F")
_gen_vals64(
((B + _TPB - 1) // _TPB,),
(_TPB,),
(
vals,
cp.int32(L),
cp.int32(d),
cp.uint64(start),
cp.int32(B),
V,
cp.int32(d),
),
)
yield V
start += B
def guess_batches_gpu(r: int, d: int, batch_size: int, choose_dev: cp.ndarray = None):
"""
Generate (G, d) on the GPU in lexicographic order.
choose_dev: optional C(u, j) table (if None, it is built and stored on the device).
"""
choose = choose_dev if choose_dev is not None else _build_choose_table_dev(r, d)
total = math.comb(r, d)
assert total < (1 << 64), "C(r, d) too large for uint64."
start = 0
while start < total:
G = min(batch_size, total - start)
idxs_gpu = cp.empty((G, d), dtype=cp.int32) # C-order
grid = ((G + _TPB - 1) // _TPB,)
_kernel_comb(
grid,
(_TPB,),
(
choose,
cp.int32(r),
cp.int32(d),
cp.uint64(start),
cp.int32(G),
idxs_gpu,
cp.int32(choose.shape[1]),
),
)
yield idxs_gpu
start += G
def _recompute_candidate_fp64(
basis,
b_host,
A,
removed,
m,
scaling_factor_y,
idxs_gpu,
V_gpu,
k,
has_tau,
target_estimation,
):
"""
Recompute in FP64 *from the basis* (QR, P, solve, rounding) for candidate k.
"""
# Map index k -> (g, b) dans la matrice Y de taille M = G*B
int(idxs_gpu.shape[0])
Bcnt = int(V_gpu.shape[1])
g = k // Bcnt
b = k % Bcnt
# ----- tout en float64 -----
B64 = cp.asarray(basis, dtype=cp.float64, order="F").T # (n,n)
b64 = cp.asarray(b_host, dtype=cp.float64)
b_used64 = b64[:-1] if has_tau else b64
A64 = cp.asarray(A[:m, :], dtype=cp.float64, order="F")[
:, cp.asarray(removed, dtype=cp.int32)
]
Q64, R64 = cp.linalg.qr(B64, mode="reduced")
y064 = Q64.T @ b_used64
T64 = cp.asfortranarray(Q64.T[:, -m:])
P64 = T64 @ A64 # (n, r)
# Construire E pour (g, b)
idxs_g = idxs_gpu[g]
Vb64 = cp.asarray(V_gpu[:, b], dtype=cp.float64)
E64 = P64[:, idxs_g] @ Vb64
Y64 = y064 - (scaling_factor_y * E64)
C64 = solve_triangular(R64, Y64)
Z64 = cp.rint(C64)
S64 = Y64 - R64 @ Z64
# Vérif seuil en FP64
thr64 = float(np.dot(target_estimation, target_estimation))
if float(cp.sum(S64 * S64)) <= thr64:
bprime64 = Q64 @ S64
bprime64 = cp.rint(bprime64).astype(cp.int64)
return cp.asnumpy(bprime64), True
return None, False
# ---------- GPU: Babai nearest-plane en FP64 pur ----------
def babai_gpu_fp64(B, t, do_qr_reduce=True):
"""
B: (n,n) ndarray int/float (will be cast to float64)
t: (n,) ndarray int/float (will be cast to float64)
Return:
dict(v, z, resid2, t_sec)
- v = B z (numpy.float64)
- z = coeffs (numpy.int64)
"""
t0 = time.time()
# Cast et mise en mémoire GPU
B_gpu = cp.asarray(
np.asarray(B, dtype=np.float64), dtype=cp.float64, order="F"
) # (n,n)
t_gpu = cp.asarray(np.asarray(t, dtype=np.float64), dtype=cp.float64)
# QR en 64 bits (sur B^T dans cette version)
Q, R = cp.linalg.qr(B_gpu.T, mode="reduced") if do_qr_reduce else (None, None)
if do_qr_reduce:
y = Q.T @ t_gpu
z = cp.rint(solve_triangular(R, y))
v = B_gpu.T @ z
resid = t_gpu - v
out = {
"v": cp.asnumpy(cp.rint(v)).astype(np.int64),
"z": cp.asnumpy(z).astype(np.int64),
"resid2": float(cp.dot(resid, resid).get()),
"t_sec": time.time() - t0,
}
return out
# ---------- GPU: Babai nearest-plane en FP64 pur ----------
def babai_gpu_fp64_nr(B, t, do_qr_reduce=True):
"""
B: (n,n) ndarray int/float (will be cast to float64)
t: (n,) ndarray int/float (will be cast to float64)
Return:
dict(v, z, resid2, t_sec)
- v = B z (numpy.float64)
- z = coeffs (numpy.int64)
"""
t0 = time.time()
# Cast et mise en mémoire GPU
B_gpu = cp.asarray(
np.asarray(B, dtype=np.float64), dtype=cp.float64, order="F"
) # (n,n)
t_gpu = cp.asarray(np.asarray(t, dtype=np.float64), dtype=cp.float64)
# QR en 64 bits (sur B^T dans cette version)
Q, R = cp.linalg.qr(B_gpu.T, mode="reduced") if do_qr_reduce else (None, None)
if do_qr_reduce:
y = Q.T @ t_gpu
U = cp.empty_like(y)
diag = cp.ascontiguousarray(cp.diag(R))
inv_diag = 1.0 / diag
nearest_plane_gpu(
R, y[:, None], U[:, None], __babai_ranges(B.shape[1]), diag, inv_diag
)
v = t_gpu + B_gpu.T @ U
resid = t_gpu - v
z = resid
out = {
"v": cp.asnumpy(cp.rint(v)).astype(np.int64),
"z": cp.asnumpy(cp.rint(z)).astype(np.int64),
"resid2": float(cp.dot(resid, resid).get()),
"t_sec": time.time() - t0,
}
return out
# ---------- CPU fpylll : choisit auto CVP.babai si t entier, sinon GSO.Mat.babai ----------
def babai_fpylll_auto(B_int_like, t_vec, prec_bits=64, do_reduce=False):
"""
B_int_like : integer matrix (typical embedding structure -> exact)
t_vec : target; if integer -> CVP.babai, otherwise -> GSO.Mat.babai (mpfr)
Return:
dict(v, z|None, resid2, t_sec, mode, prec_bits)
"""
t0 = time.time()
B = IntegerMatrix.from_matrix(B_int_like)
# test "entier" robuste
t_np = np.asarray(t_vec, dtype=np.float64)
np.allclose(t_np, np.rint(t_np), rtol=0, atol=0)
if False:
v = CVP.babai(B, list(map(int, np.rint(t_np))))
v_np = np.array(v, dtype=np.int64)
mode = "CVP.babai"
z = None
else:
FPLLL.set_precision(int(prec_bits))
M = GSO.Mat(B, float_type="mpfr", update=True)
w = M.babai(list(map(float, t_np)))
v_np = np.array(B.multiply_left(w), dtype=object)
mode = "GSO.Mat.babai"
z = None
resid2 = float(np.sum((t_np.astype(np.float64) - v_np.astype(np.float64)) ** 2))
return {
"v": v_np,
"z": None if z is None else z,
"resid2": resid2,
"t_sec": time.time() - t0,
"mode": mode,
"prec_bits": prec_bits,
}
# Try comparaison with FPLLL
def compare_babai(
B,
t,
fpylll_prec_bits=512,
fpylll_reduce=False,
bkz_beta=None,
bkz_loops=1,
gpu_qr=True,
):
# CPU (fpylll)
# cpu = babai_fpylll_auto(B, t, prec_bits=fpylll_prec_bits, do_reduce=fpylll_reduce)
# GPU (CuPy fp64)
gpu = babai_gpu_fp64(B, t, do_qr_reduce=gpu_qr)
gpu_nr = babai_gpu_fp64_nr(B, t, do_qr_reduce=gpu_qr)
same_v = np.array_equal(
np.asarray(np.rint(gpu_nr["v"]), dtype=np.int64),
np.asarray(np.rint(gpu["v"]), dtype=np.int64),
)
print(same_v)
print(gpu_nr["v"])
print(gpu["v"])
return None
def center_lift(x, q):
r = np.remainder(x, q) # in [0, q)
r = np.where(r > q / 2, r - q, r) # to (−q/2, q/2]
return r
def matvec_mod_q(A, s, q, block=256):
m, n = A.shape
acc = np.zeros(m, dtype=object) # sûr mais plus lent
for j0 in range(0, n, block):
j1 = min(n, j0 + block)
acc = (acc + (A[:, j0:j1].astype(object) @ s[j0:j1].astype(object))) % q
return np.asarray(acc, dtype=object)
def lwe_error_from_secret_safe(A, b, s, q):
r = (b.astype(object) - matvec_mod_q(A, s, q)) % q
e = ((r + q // 2) % q) - q // 2 # center lift version object-safe
return np.asarray(e, dtype=int)
def svp_babai_fp32(
basis,
eta,
columns_to_keep,
A,
b_vec,
tau,
n,
k,
m,
secret_possible_values,
search_space_dim,
target_estimation,
scaling_factor_y,
hw,
):
timestart = time.time()
basis_gpu = cp.asarray(basis, dtype=cp.float32, order="F")
b_host = np.array(b_vec.list(), dtype=basis.dtype)
b_gpu = cp.asarray(b_host, dtype=cp.float32)
subA_gpu = cp.asarray(A[:m, :], dtype=cp.float32)
removed = [j for j in range(n) if j not in columns_to_keep]
C_all = subA_gpu[:, cp.asarray(removed, dtype=cp.int32)] # (m, r)
r = C_all.shape[1]
has_tau = b_gpu.shape[0] == basis_gpu.shape[0] + 1
b_used_gpu = b_gpu[:-1] if has_tau else b_gpu
B_gpu = basis_gpu.T # (n, n)
# try to avoid error from QR
# Q_gpu, R_gpu = cp.linalg.qr(B_gpu, mode='reduced')
Q_gpu, R_gpu = cp.linalg.qr(
cp.asarray(basis, dtype=cp.float64, order="F").T, mode="reduced"
)
y0 = Q_gpu.T @ b_used_gpu # (n,)
tail_slice = slice(-m, None) # <-- inconditionnel
T = cp.asfortranarray(Q_gpu.T[:, tail_slice]) # d×m
P = T @ C_all
c0 = solve_triangular(R_gpu, y0) # (nR,)
U = solve_triangular(R_gpu, P) # (nR, r) # TRSM multi-RHS
U, c0 = U.astype(cp.float32), c0.astype(cp.float32)
Q_gpu, R_gpu = Q_gpu.astype(cp.float32), R_gpu.astype(cp.float32)
# try without guess
Z0 = cp.rint(c0)
S0 = y0 - R_gpu @ Z0
norm0 = cp.sum(S0 * S0)
norm_wanted2 = cp.asarray(float(np.dot(target_estimation, target_estimation)))
if bool((norm0 <= norm_wanted2).get()):
bprime0 = b_used_gpu - B_gpu @ Z0
finish = time.time()
return cp.asnumpy(bprime0), finish - timestart
GUESS_BATCH = 4096
VALUE_BATCH = 512
PRE_SECRET_TEST = hw + 2
nR = int(y0.shape[0])
choose_dev = _build_choose_table_dev(r, search_space_dim + 1)
vals_dev = cp.asarray(secret_possible_values, dtype=cp.float32)
B_head32 = cp.asfortranarray(B_gpu[: n - k, :].astype(cp.float32, copy=False))
B_head_opti = cp.asfortranarray(
B_gpu[:PRE_SECRET_TEST, :].astype(cp.float32, copy=False)
)
# 3h16 to 2h02 with only check secret target (on 1641247665 * 4**4 try) and up to 1h22 with pre_test and increase batch size
for d in range(1, search_space_dim + 1):
total_guesses = math.comb(r, d)
nonzero_target = hw - d
print(
f"guessing {total_guesses} number of positions of the last {d} non-zero coefficients of the secret"
)
num_guess_batches = (total_guesses + GUESS_BATCH - 1) // GUESS_BATCH
for idxs_gpu in tqdm(
guess_batches_gpu(r, d, GUESS_BATCH, choose_dev=choose_dev),
total=num_guess_batches,
desc=f"Guess-batch (d={d})",
):
U_batch = U[:, idxs_gpu] # (nR, G, d)
G = idxs_gpu.shape[0]
U_flat = U_batch.reshape(nR * G, d)
for V_gpu in value_batches_fp32_gpu(vals_dev, d, VALUE_BATCH):
B = V_gpu.shape[1]
M = G * B
# just do a float64 2min30 and 1min40 for a full FP32
E_flat = U_flat @ V_gpu
# suppose no scaling factor here
Y = c0[:, None] - E_flat.reshape(nR, M)
Z = cp.rint(Y)
# precheck for don't compute whole secret each time
S_test = B_head_opti @ Z
hit_test = cp.any(
(cp.abs(S_test) >= 0.5).sum(axis=0, dtype=cp.int32)
<= nonzero_target
)
if bool(hit_test):
S = B_head32 @ (Z) # closest to the lattice
hit = cp.any(
(cp.abs(S) >= 0.5).sum(axis=0, dtype=cp.int32) == nonzero_target
)
if bool(hit):
# find the index of the hit
s_int = cp.rint(S).astype(
cp.int32
) # discretize to integers before counting
nz_counts = cp.count_nonzero(s_int, axis=0) # shape: (M,)
mask_hw = (
nz_counts == nonzero_target
) # boolean mask over candidates (M,)
idx = cp.where(mask_hw)[0]
k = int(idx[0].get())
# just return this
return cp.asnumpy(
((B_gpu @ (Y - Z))[:, k]).astype(cp.int64)
), time.time() - timestart
# or recompute all in float64 here for recover well
bprime64, ok = _recompute_candidate_fp64(
basis,
b_host,
A,
removed,
m,
scaling_factor_y,
idxs_gpu,
V_gpu,
k,
has_tau,
target_estimation,
)
print(bprime64)
if ok:
return bprime64, time.time() - timestart
bprime0 = Q_gpu @ S0
finish = time.time()
return cp.asnumpy(bprime0), finish - timestart
@cache
def __reduction_ranges(n):
"""
Return list of ranges that needs to be reduced.
More generally, it returns, without using recursion, the list that would be
the output of the following Python program:
<<<BEGIN CODE>>>
def rec_range(n):
bc, res = [], []
def F(l, r):
if l == r:
return
if l + 1 == r:
bc.append(l)
else:
m = (l + r) // 2
F(l, m)
F(m, r)
res.append((l, m, r))
return F(0, n)
<<<END CODE>>>
:param n: the length of the array that requires reduction
:return: pair containing `the base_cases` and `result`.
`base_cases` is a list of indices `i` such that:
`i + 1` needs to be reduced w.r.t. `i`.
`result` is a list of triples `(i, j, k)` such that:
`[j:k)` needs to be reduced w.r.t. `[i:j)`.
The guarantee is that for any 0 <= i < j < n:
1) `i in base_cases && j = i + 1`,
OR
2) there is a triple (u, v, w) such that `i in [u, v)` and `j in [v, w)`.
"""
bit_shift, parts, result, base_cases = 1, 1, [], []
while parts < n:
left_bound, left_idx = 0, 0
for i in range(1, parts + 1):
right_bound = left_bound + 2 * n
mid_idx = (left_bound + n) >> bit_shift
right_idx = right_bound >> bit_shift
if right_idx > left_idx + 1:
# Only consider nontrivial intervals
if right_idx == left_idx + 2:
# Return length 2 intervals separately to unroll base case.
base_cases.append(left_idx)
else:
# Properly sized interval:
result.append((left_idx, mid_idx, right_idx))
left_bound, left_idx = right_bound, right_idx
parts *= 2
bit_shift += 1
return base_cases, list(reversed(result))
@cache
def __babai_ranges(n):
# Assume all indices are base cases initially
range_around = [False] * n
for i, j, k in __reduction_ranges(n)[1]:
# Mark node `j` as responsible to reduce [i, j) wrt [j, k) once Babai is at/past index j.
range_around[j] = (i, k)
return range_around
@cp.fuse()
def reduce_step(Tj, inv_d, d):
u = -cp.rint(Tj * inv_d)
return u, Tj + d * u
def nearest_plane_gpu(R, T, U, range_around, diag, inv_diag):
"""
In-place Babai nearest plane on GPU.
R: (n,n) upper-triangular, cupy ndarray (float32/float64), Fortran order preferred
T: (n,N) targets, cupy ndarray, Fortran order preferred
U: (n,N) integer coeffs (same dtype as T is ok, we rint then cast), Fortran order preferred
range_around: precomputed index ranges like your __babai_ranges(n)
either False or a tuple (i, k) for each j
Side-effects: updates T <- T + R @ U and fills U.
"""
Rm = R
Tm = T