-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathpermute.cc
More file actions
1880 lines (1633 loc) · 67.3 KB
/
permute.cc
File metadata and controls
1880 lines (1633 loc) · 67.3 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
// Copyright 2023 Ant Group Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "libspu/kernel/hal/permute.h"
#include <algorithm>
#include "libspu/core/bit_utils.h"
#include "libspu/core/context.h"
#include "libspu/core/trace.h"
#include "libspu/core/vectorize.h"
#include "libspu/kernel/hal/constants.h"
#include "libspu/kernel/hal/polymorphic.h"
#include "libspu/kernel/hal/prot_wrapper.h"
#include "libspu/kernel/hal/public_helper.h"
#include "libspu/kernel/hal/random.h"
#include "libspu/kernel/hal/ring.h"
#include "libspu/kernel/hal/shape_ops.h"
#include "libspu/kernel/hal/type_cast.h"
#include "libspu/kernel/hal/utils.h"
#include "libspu/spu.h"
namespace spu::kernel::hal {
namespace internal {
inline int64_t _get_owner(const Value &x) {
return x.storage_type().as<Private>()->owner();
}
inline bool _has_same_owner(const Value &x, const Value &y) {
return _get_owner(x) == _get_owner(y);
}
hal::CompFn _get_cmp_func(SPUContext *ctx, int64_t num_keys,
SortDirection direction, bool append_rand = false) {
hal::CompFn comp_fn = [ctx, num_keys, direction, append_rand](
absl::Span<const spu::Value> values) -> spu::Value {
auto scalar_cmp = [direction](spu::SPUContext *ctx, const spu::Value &lhs,
const spu::Value &rhs) {
if (direction == SortDirection::Ascending) {
return hal::less(ctx, lhs, rhs);
}
return hal::greater(ctx, lhs, rhs);
};
spu::Value k1 = hal::constant(ctx, true, DT_I1, values[0].shape());
spu::Value pre_equal = k1;
spu::Value result = scalar_cmp(ctx, values[0], values[1]);
// the idea here is that if the two values of the last key is equal,
// than we compare the two values of the current key, and iteratively to
// update the result which indicates whether to swap values
int64_t idx;
for (idx = 2; idx < num_keys * 2; idx += 2) {
pre_equal = hal::bitwise_and(
ctx, pre_equal, hal::equal(ctx, values[idx - 2], values[idx - 1]));
auto current = scalar_cmp(ctx, values[idx], values[idx + 1]);
current = hal::bitwise_and(ctx, pre_equal, current);
result = hal::bitwise_or(ctx, result, current);
}
// append rand value to avoid the same key "pitfall" in partition-based
// algorithms (e.g. quick-sort, quick-select).
if (append_rand) {
// must use secret bits here, otherwise some infos will leak
auto rand_bits = hal::random(ctx, VIS_SECRET, DT_I1, values[0].shape());
// equal has better performance for aby3
// cmp+andbb has better performance for semi2k now
pre_equal = hal::bitwise_and(
ctx, pre_equal, hal::equal(ctx, values[idx - 2], values[idx - 1]));
auto current = hal::bitwise_and(ctx, pre_equal, rand_bits);
result = hal::bitwise_or(ctx, result, current);
}
return result;
};
return comp_fn;
}
bool _has_efficient_shuffle(SPUContext *ctx) {
const auto prot = ctx->config().protocol;
// semi2k and aby3 have highly efficient constant round implementation.
return prot == ProtocolKind::SEMI2K || prot == ProtocolKind::ABY3;
}
bool _check_method_require(SPUContext *ctx, RuntimeConfig::SortMethod method) {
bool pass = false;
switch (method) {
case RuntimeConfig::SORT_RADIX:
pass = ctx->hasKernel("rand_perm_m") && ctx->hasKernel("perm_am") &&
ctx->hasKernel("perm_ap") && ctx->hasKernel("inv_perm_am") &&
ctx->hasKernel("inv_perm_ap");
break;
case RuntimeConfig::SORT_QUICK:
// quick sort only requires small subsets of shuffle kernels, but need
// rand_b kernel to avoid calling of a2b.
pass = ctx->hasKernel("rand_perm_m") && ctx->hasKernel("perm_am") &&
ctx->hasKernel("rand_b");
break;
case RuntimeConfig::SORT_NETWORK:
// sort network is a general method which can be used for all MPC
// protocols.
pass = true;
break;
default:
SPU_THROW("Should not reach here");
}
return pass;
}
RuntimeConfig::SortMethod select_sort_method(
SPUContext *ctx, RuntimeConfig::SortMethod preferred_method) {
SPU_ENFORCE(preferred_method != RuntimeConfig::SORT_DEFAULT);
// if the preferred method is not supported, fall back to sorting network now.
const RuntimeConfig::SortMethod fallback_method = RuntimeConfig::SORT_NETWORK;
switch (preferred_method) {
case RuntimeConfig::SORT_RADIX:
if (internal::_check_method_require(ctx, RuntimeConfig::SORT_RADIX)) {
return preferred_method;
}
break;
case RuntimeConfig::SORT_QUICK:
if (internal::_check_method_require(ctx, RuntimeConfig::SORT_QUICK)) {
return preferred_method;
}
break;
case RuntimeConfig::SORT_NETWORK:
// always true now.
if (internal::_check_method_require(ctx, RuntimeConfig::SORT_NETWORK)) {
return preferred_method;
}
SPU_THROW("should not reach here");
break;
default:
SPU_THROW("should not reach here");
}
return fallback_method;
}
std::vector<spu::Value> fallback_sort1d(SPUContext *ctx,
absl::Span<spu::Value const> inputs,
int64_t num_keys,
SortDirection direction,
bool is_stable = false) {
auto comp_fn = _get_cmp_func(ctx, num_keys, direction);
Visibility vis = std::all_of(inputs.begin(), inputs.begin() + num_keys,
[](const spu::Value &v) { return v.isPublic(); })
? VIS_PUBLIC
: VIS_SECRET;
// sort1d supports stable sorting when comparator visibility is PUBLIC
// (e.g., when all keys are public). When comparator visibility is SECRET,
// it falls back to an odd-even sorting network, which is an unstable
// sorting method.
auto ret = sort1d(ctx, inputs, comp_fn, vis, is_stable);
return ret;
}
void _hint_nbits(const Value &a, size_t nbits) {
if (a.storage_type().isa<BShare>()) {
const_cast<Type &>(a.storage_type()).as<BShare>()->setNbits(nbits);
}
}
// generate inverse permutation
Index _inverse_index(const Index &p) {
Index q(p.size());
const auto n = static_cast<int64_t>(p.size());
for (int64_t i = 0; i < n; ++i) {
q[p[i]] = i;
}
return q;
}
spu::Value _2s(SPUContext *ctx, const Value &x) {
if (x.isPublic()) {
return _p2s(ctx, x);
} else if (x.isPrivate()) {
return _v2s(ctx, x);
}
return x;
}
Value _permute_1d(SPUContext *, const Value &x, const Index &indices) {
SPU_ENFORCE(x.shape().size() == 1);
return Value(x.data().linear_gather(indices), x.dtype());
}
Value _prefix_sum(SPUContext *ctx, const Value &x) {
SPU_ENFORCE(x.shape().ndim() == 2U && x.shape()[0] == 1,
"x should be 1-row matrix");
auto x_v = hal::reshape(ctx, x, {x.numel()});
auto ret = hal::associative_scan(hal::_add, ctx, x_v);
return hal::reshape(ctx, ret, {1, x.numel()});
}
void _cmp_swap(SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value> values_to_sort, const Index &lhs_indices,
const Index &rhs_indices) {
size_t num_operands = values_to_sort.size();
std::vector<spu::Value> values;
values.reserve(2 * num_operands);
for (size_t i = 0; i < num_operands; ++i) {
values.emplace_back(values_to_sort[i].data().linear_gather(lhs_indices),
values_to_sort[i].dtype());
values.emplace_back(values_to_sort[i].data().linear_gather(rhs_indices),
values_to_sort[i].dtype());
}
spu::Value predicate = comparator_body(values);
predicate = hal::_prefer_a(ctx, predicate);
for (size_t i = 0; i < num_operands; ++i) {
const auto &fst = values[2 * i];
const auto &sec = values[2 * i + 1];
auto greater = select(ctx, predicate, fst, sec);
auto less = sub(ctx, add(ctx, fst, sec), greater);
values_to_sort[i].data().linear_scatter(greater.data(), lhs_indices);
values_to_sort[i].data().linear_scatter(less.data(), rhs_indices);
}
}
// Secure Odd-even mergesort
// Ref:
// https://hwlang.de/algorithmen/sortieren/networks/oemen.htm
std::vector<spu::Value> odd_even_merge_sort(
SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value const> inputs) {
// make a copy for inplace sort
std::vector<spu::Value> ret;
for (auto const &input : inputs) {
spu::Value casted;
if (!input.isSecret()) {
// we can not linear_scatter a secret value to a public operand
casted = _2s(ctx, input.clone()).setDtype(input.dtype());
} else {
casted = input.clone();
}
// we can not linear_scatter an ashare value to a bshare operand
casted = _prefer_a(ctx, casted);
ret.emplace_back(std::move(casted));
}
// sort by per network layer for memory optimizations, sorting N elements
// needs log2(N) stages, and the i_th stage has i layers, which means the
// same latency cost as BitonicSort but less _cmp_swap unit.
const auto n = inputs.front().numel();
for (int64_t max_gap_in_stage = 1; max_gap_in_stage < n;
max_gap_in_stage += max_gap_in_stage) {
for (int64_t step = max_gap_in_stage; step > 0; step /= 2) {
// collect index pairs that can be computed parallelly.
Index lhs_indices;
Index rhs_indices;
for (int64_t j = step % max_gap_in_stage; j + step < n;
j += step + step) {
for (int64_t i = 0; i < step; i++) {
auto lhs_idx = i + j;
auto rhs_idx = i + j + step;
if (rhs_idx >= n) break;
auto range = max_gap_in_stage + max_gap_in_stage;
if (lhs_idx / range == rhs_idx / range) {
lhs_indices.emplace_back(lhs_idx);
rhs_indices.emplace_back(rhs_idx);
}
}
}
_cmp_swap(ctx, comparator_body, absl::MakeSpan(ret), lhs_indices,
rhs_indices);
}
}
return ret;
}
void Swap(absl::Span<spu::Value> arr, const Index &lhs_indices,
const Index &rhs_indices) {
if (lhs_indices.empty() ||
(lhs_indices.size() == 1 && rhs_indices.size() == 1 &&
lhs_indices[0] == rhs_indices[0])) {
return;
}
const auto num_operands = arr.size();
for (size_t i = 0; i < num_operands; ++i) {
auto lhs_arr = arr[i].data().linear_gather(lhs_indices);
auto rhs_arr = arr[i].data().linear_gather(rhs_indices);
arr[i].data().linear_scatter(lhs_arr, rhs_indices);
arr[i].data().linear_scatter(rhs_arr, lhs_indices);
}
}
void CompSwapSingle(SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value> arr, int64_t lo, int64_t hi,
const TopKConfig &config) {
if (lo == hi) {
return;
}
// const auto num_operands = arr.size();
std::vector<Value> values;
values.emplace_back(slice_scalar_at(ctx, arr[0], {lo}));
values.emplace_back(slice_scalar_at(ctx, arr[0], {hi}));
if (config.confusion) {
values.emplace_back(slice_scalar_at(ctx, arr[1], {lo}));
values.emplace_back(slice_scalar_at(ctx, arr[1], {hi}));
}
auto predicate = comparator_body(values);
auto _predicate = getBooleanValue(ctx, hal::reveal(ctx, predicate));
if (!_predicate) {
Swap(arr, {lo}, {hi});
}
}
void HandleSmallArray(SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value> arr, int64_t lo, int64_t hi,
const TopKConfig &config) {
if (hi == lo + 1) {
CompSwapSingle(ctx, comparator_body, arr, lo, hi, config);
}
}
std::vector<Value> _construct_cmp_values(
SPUContext *ctx, const std::vector<std::pair<int64_t, int64_t>> &intervals,
absl::Span<spu::Value const> arr, const int64_t quick_sort_thres,
const int64_t num_keys) {
int64_t lo;
int64_t hi;
int64_t left;
int64_t right;
std::vector<std::vector<Value>> cmp_values(2 * num_keys);
for (auto &values : cmp_values) {
values.reserve(intervals.size());
}
for (const auto &interval : intervals) {
std::tie(lo, hi) = interval;
if (hi - lo <= quick_sort_thres) {
continue;
}
left = lo + 1;
right = hi;
for (int64_t i = 0; i < num_keys; i++) {
// pivot
cmp_values[2 * i].push_back(broadcast_to(
ctx, slice_scalar_at(ctx, arr[i], {lo}), {right - left + 1}));
// others
cmp_values[2 * i + 1].push_back(slice(ctx, arr[i], {left}, {right + 1}));
}
}
// no need to quick sort
if (cmp_values[0].empty()) {
return {};
}
std::vector<Value> ret;
ret.reserve(2 * num_keys);
for (int64_t i = 0; i < 2 * num_keys; i++) {
ret.push_back(concatenate(ctx, cmp_values[i], 0));
}
return ret;
}
bool Partition(SPUContext *ctx, const int64_t num_keys,
const CompFn &comparator_body, absl::Span<spu::Value> arr,
std::vector<std::pair<int64_t, int64_t>> &intervals) {
if (intervals.empty()) {
return false;
}
int64_t quick_sort_thres = ctx->config().quick_sort_threshold;
int64_t lo; // left end of current interval
int64_t hi; // right end of current interval
int64_t left; // location of left pointer
int64_t right; // location of right pointer
int64_t mid; // location of pivot element after partition
auto values =
_construct_cmp_values(ctx, intervals, arr, quick_sort_thres, num_keys);
if (values.empty()) {
return false;
}
auto predicate = comparator_body(values);
auto _predicate = dump_public_as<bool>(ctx, hal::reveal(ctx, predicate));
Index lhs_indices;
Index rhs_indices;
Index pivot_indices;
Index mid_indices;
// save partition output, i.e. (lo, mid, hi), where mid is the location of
// pivot after partition.
std::vector<std::tuple<int64_t, int64_t, int64_t>> pos;
// save the intervals that do not need quick sort anymore.
std::vector<std::pair<int64_t, int64_t>> pass_vec;
int64_t length = 0;
for (auto item : intervals) {
std::tie(lo, hi) = item;
if (hi - lo <= quick_sort_thres) {
pass_vec.emplace_back(lo, hi);
continue;
}
left = lo + 1;
right = hi;
auto offset = left;
// use two pointer for partition
for (;;) {
while (right >= left && !_predicate[left - offset + length]) {
left++;
}
while (right >= left && _predicate[right - offset + length]) {
right--;
}
if (right < left) {
break;
}
lhs_indices.emplace_back(left);
rhs_indices.emplace_back(right);
left++;
right--;
}
length += (hi - lo);
pivot_indices.emplace_back(lo);
mid_indices.emplace_back(right);
pos.emplace_back(lo, right, hi);
}
Swap(arr, lhs_indices, rhs_indices);
// swap the pivot
Swap(arr, pivot_indices, mid_indices);
intervals.swap(pass_vec);
intervals.reserve(2 * intervals.size());
while (!pos.empty()) {
std::tie(lo, mid, hi) = pos.back();
pos.pop_back();
if (lo < mid) {
intervals.emplace_back(lo, mid - 1);
}
if (mid < hi) {
intervals.emplace_back(mid + 1, hi);
}
}
return true;
}
// this algorithm is mainly adopted from odd-even mergesort, but we can reveal
// the comparison because of shuffling
void mergesort(SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value> arr,
std::vector<std::pair<int64_t, int64_t>> &intervals) {
const auto N = arr.front().numel();
int64_t logn = Log2Ceil(N);
// max depth for odd-even merge network
int64_t depth = ((logn + 1) * logn) / 2;
std::vector<Index> lhs_indices(depth);
std::vector<Index> rhs_indices(depth);
int64_t lo;
int64_t hi;
for (auto item : intervals) {
std::tie(lo, hi) = item;
if (hi - lo <= 0) {
continue;
}
int64_t n = hi - lo + 1;
int64_t cnt = 0;
for (int64_t max_gap_in_stage = 1; max_gap_in_stage < n;
max_gap_in_stage += max_gap_in_stage) {
for (int64_t step = max_gap_in_stage; step > 0; step /= 2) {
for (int64_t j = step % max_gap_in_stage; j + step < n;
j += step + step) {
auto range = max_gap_in_stage + max_gap_in_stage;
for (int64_t i = 0; i < step; i++) {
auto lhs_idx = i + j;
auto rhs_idx = i + j + step;
if (rhs_idx >= n) {
break;
}
if (lhs_idx / range == rhs_idx / range) {
lhs_indices[cnt].emplace_back(lhs_idx + lo);
rhs_indices[cnt].emplace_back(rhs_idx + lo);
}
}
}
cnt += 1;
}
}
}
size_t num_operands = arr.size();
for (size_t i = 0; i < lhs_indices.size(); i++) {
if (lhs_indices[i].empty()) {
continue;
}
Index lhs_indice;
Index rhs_indice;
std::vector<spu::Value> values;
values.reserve(2 * num_operands);
for (size_t j = 0; j < num_operands; ++j) {
values.emplace_back(arr[j].data().linear_gather(lhs_indices[i]),
arr[j].dtype());
values.emplace_back(arr[j].data().linear_gather(rhs_indices[i]),
arr[j].dtype());
}
auto predicate = comparator_body(values);
auto _predicate = dump_public_as<bool>(ctx, hal::reveal(ctx, predicate));
for (size_t k = 0; k < _predicate.size(); k++) {
if (!_predicate[k]) {
lhs_indice.emplace_back(lhs_indices[i][k]);
rhs_indice.emplace_back(rhs_indices[i][k]);
}
}
Swap(arr, lhs_indice, rhs_indice);
}
}
std::vector<spu::Value> QuickMergesort(SPUContext *ctx, const int64_t num_keys,
const CompFn &quick_comp,
const CompFn &merge_comp,
absl::Span<spu::Value const> inputs) {
// we do not need to copy or _2s here because of the secret shuffling.
std::vector<spu::Value> ret(inputs.begin(), inputs.end());
const auto n = inputs.front().numel();
std::vector<std::pair<int64_t, int64_t>> intervals;
intervals.emplace_back(0, n - 1);
int64_t quicksort_num = 0;
// set max depth to avoid infinite loop
int64_t depth = 1000;
bool need_quick_sort = true;
while (!intervals.empty()) {
need_quick_sort =
Partition(ctx, num_keys, quick_comp, absl::MakeSpan(ret), intervals);
quicksort_num += 1;
if (!need_quick_sort || (quicksort_num == depth)) {
break;
}
}
if (intervals.empty()) {
return ret;
}
mergesort(ctx, merge_comp, absl::MakeSpan(ret), intervals);
return ret;
}
std::vector<spu::Value> PrepareSort(SPUContext *ctx,
absl::Span<spu::Value const> inputs) {
std::vector<spu::Value> inp;
inp.reserve(inputs.size());
auto rand_perm = _rand_perm_s(ctx, inputs.front().shape());
// use a random permutation to break link of values, such that the following
// comparison can be revealed without loss of information.
for (const auto &input : inputs) {
inp.emplace_back(std::move(
_perm_ss(ctx, _2s(ctx, input), rand_perm).setDtype(input.dtype())));
}
return inp;
}
std::vector<spu::Value> quick_sort(SPUContext *ctx,
absl::Span<spu::Value const> inputs,
int64_t num_keys, SortDirection direction) {
auto inp = PrepareSort(ctx, inputs);
// quick sort will append extra random key
auto quick_comp = _get_cmp_func(ctx, num_keys, direction, true);
// in merge sort stage, only normal keys are used for comparison
auto merge_comp = _get_cmp_func(ctx, num_keys, direction);
auto ret = QuickMergesort(ctx, num_keys, quick_comp, merge_comp,
absl::MakeSpan(inp));
return ret;
}
void TwoWayPartition(SPUContext *ctx, const CompFn &comparator_body,
absl::Span<spu::Value> arr, int64_t lo, int64_t hi,
const TopKConfig &config,
std::vector<std::pair<int64_t, int64_t>> &intervals) {
// Just use first element as pivot, so left=lo+1
auto left = lo + 1;
auto right = hi;
// collect and do comparison once
// const auto num_operands = arr.size();
std::vector<Value> values;
// arr contains: value, random_value, index
// values: pivot_value, rest_value, pivot_rand, rest_rand
values.push_back(broadcast_to(ctx, slice_scalar_at(ctx, arr[0], {lo}),
{right - left + 1}));
values.push_back(slice(ctx, arr[0], {left}, {right + 1}));
if (config.confusion) {
values.push_back(broadcast_to(ctx, slice_scalar_at(ctx, arr[1], {lo}),
{right - left + 1}));
values.push_back(slice(ctx, arr[1], {left}, {right + 1}));
}
auto predicate = comparator_body(values);
auto _predicate = dump_public_as<bool>(ctx, hal::reveal(ctx, predicate));
auto offset = left;
Index lhs_indices;
Index rhs_indices;
// use two pointer for partition
for (;;) {
while (right >= left && !_predicate[left - offset]) {
left++;
}
while (right >= left && _predicate[right - offset]) {
right--;
}
if (right < left) {
break;
}
lhs_indices.emplace_back(left);
rhs_indices.emplace_back(right);
left++;
right--;
}
// do all non-overlaping swap
Swap(arr, lhs_indices, rhs_indices);
// swap the pivot
Swap(arr, {lo}, {right});
if (config.k_lo - 1 < right && right < config.k_hi - 1) {
intervals.emplace_back(lo, right - 1);
intervals.emplace_back(left, hi);
return;
}
if (right >= config.k_hi - 1) {
hi = right - 1;
}
if (right <= config.k_lo - 1) {
lo = left;
}
intervals.emplace_back(lo, hi);
}
std::vector<spu::Value> QuickSelectTopk(SPUContext *ctx,
const CompFn &comparator_body,
absl::Span<spu::Value> input,
const TopKConfig &config) {
const auto n = input.front().numel();
int64_t lo;
int64_t hi;
// save value and index
std::vector<Value> out;
// to support multiple ks, maintain all intervals to search
std::vector<std::pair<int64_t, int64_t>> intervals;
// first seach the whole interval
intervals.emplace_back(0, n - 1);
while (!intervals.empty()) {
std::tie(lo, hi) = intervals.back();
intervals.pop_back();
if (hi <= lo + 1) {
// exit loop when interval<=2
HandleSmallArray(ctx, comparator_body, input, lo, hi, config);
} else {
TwoWayPartition(ctx, comparator_body, input, lo, hi, config, intervals);
}
}
out.push_back(slice(ctx, input.front(), {0}, {config.k_hi}));
if (!config.value_only) {
out.push_back(slice(ctx, input.back(), {0}, {config.k_hi}));
}
return out;
}
std::vector<spu::Value> PrepareInput(SPUContext *ctx, const Value &input,
const TopKConfig &config) {
std::vector<spu::Value> inp;
// shuffle with random permutation to break link of values
auto rand_perm = _rand_perm_s(ctx, input.shape());
inp.push_back(_perm_ss(ctx, input, rand_perm).setDtype(input.dtype()));
// we concate random value to hide the data-dependant running pattern
// for quick select;
// consider an extreme case where all values are identical, two-way partition
// will run very slowly. If running multiple times and finding that it
// consistently takes a long time, it can be reasonably inferred that there is
// a significant amount of duplicate data in the original dataset. However,
// with the addition of randomness, we can essentially assume that all data
// points are unique, which would lead to a more stable runtime.
if (config.confusion) {
inp.push_back(hal::random(ctx, Visibility::VIS_SECRET, DataType::DT_F64,
input.shape()));
}
if (!config.value_only) {
auto dt =
ctx->config().field == FieldType::FM32 ? spu::DT_I32 : spu::DT_I64;
// shuffle index with the same permutation as values
inp.push_back(
_perm_ss(ctx, _p2s(ctx, hal::iota(ctx, dt, input.numel())), rand_perm)
.setDtype(dt));
}
return inp;
}
// Ref: https://eprint.iacr.org/2019/695.pdf
// Algorithm 13 Optimized inverse application of a permutation
//
// The steps are as follows:
// 1) secure shuffle <perm> as <sp>
// 2) secure shuffle <x> as <sx>
// 3) reveal securely shuffled <sp> as m
// 4) inverse permute <sx> by m and return
std::pair<std::vector<spu::Value>, spu::Value> _opt_apply_inv_perm_ss(
SPUContext *ctx, absl::Span<spu::Value const> x, const spu::Value &perm,
const spu::Value &random_perm) {
// 1. <SP> = secure shuffle <perm>
auto sp = hal::_perm_ss(ctx, perm, random_perm);
// 2. <SX> = secure shuffle <x>
std::vector<spu::Value> sx;
for (size_t i = 0; i < x.size(); ++i) {
sx.emplace_back(hal::_perm_ss(ctx, x[i], random_perm));
}
// 3. M = reveal(<SP>)
auto m = _s2p(ctx, sp);
SPU_ENFORCE_EQ(m.shape().ndim(), 1U, "perm should be 1-d tensor");
// 4. <T> = SP(<SX>)
std::vector<spu::Value> v;
for (size_t i = 0; i < sx.size(); ++i) {
auto t = hal::_inv_perm_sp(ctx, sx[i], m);
v.emplace_back(std::move(t));
}
return {v, m};
}
// Process two bit vectors in one loop
// Reference: https://eprint.iacr.org/2019/695.pdf (5.2 Optimizations)
//
// perm = _gen_inv_perm_by_bv(x, y)
// input: bit vector x, bit vector y
// bit vector y is more significant than x
// output: shared inverse permutation
//
// We can generate inverse permutation by two bit vectors in one loop.
// It needs one extra mul op and 2 times memory to store intermediate data
// than _gen_inv_perm_by_bv. But the number of invocations of
// permutation-related protocols such as SecureInvPerm or Compose will be
// reduced to half.
//
// If we process three bit vectors in one loop, it needs at least four extra
// mul ops and 2^2 times data to store intermediate data. The number of
// invocations of permutation-related protocols such as SecureInvPerm or
// Compose will be reduced to 1/3. It's latency friendly but not bandwidth
// friendly.
//
// Example:
// 1) x = [0, 1], y = [1, 0]
// 2) rev_x = [1, 0], rev_y = [0, 1]
// 3) f0 = rev_x * rev_y = [0, 0]
// f1 = x * rev_y = [0, 1]
// f2 = rev_x * y = [1, 0]
// f3 = x * y = [0, 0]
// f = [f0, f1, f2, f3] = [0, 0, 0, 1, 1, 0, 0, 0]
// 4) s[i] = s[i - 1] + f[i], s[0] = f[0]
// s = [0, 0, 0, 1, 2, 2, 2, 2]
// 5) fs = f * s
// fs = [0, 0, 0, 1, 2, 0, 0, 0]
// 6) split fs to four vector
// fsv[0] = [0, 0]
// fsv[1] = [0, 1]
// fsv[2] = [2, 0]
// fsv[3] = [0, 0]
// 7) r = fsv[0] + fsv[1] + fsv[2] + fsv[3]
// r = [2, 1]
// 8) get res by sub r by one
// res = [1, 0]
spu::Value _gen_inv_perm_by_bv(SPUContext *ctx, const spu::Value &x,
const spu::Value &y) {
SPU_ENFORCE(x.shape() == y.shape(), "x and y should has the same shape");
SPU_ENFORCE(x.shape().ndim() == 1, "x and y should be 1-d");
const auto k1 = _constant(ctx, 1U, x.shape());
auto rev_x = _sub(ctx, k1, x);
auto rev_y = _sub(ctx, k1, y);
auto f0 = _mul(ctx, rev_x, rev_y);
auto f1 = _sub(ctx, rev_y, f0);
auto f2 = _sub(ctx, rev_x, f0);
auto f3 = _sub(ctx, y, f2);
const auto numel = x.numel();
auto f = concatenate(ctx,
{unsqueeze(ctx, f0), unsqueeze(ctx, f1),
unsqueeze(ctx, f2), unsqueeze(ctx, f3)},
1);
// calculate prefix sum
auto ps = _prefix_sum(ctx, f);
// mul f and s
auto fs = _mul(ctx, f, ps);
auto fs0 = slice(ctx, fs, {0, 0}, {1, numel}, {});
auto fs1 = slice(ctx, fs, {0, numel}, {1, 2 * numel}, {});
auto fs2 = slice(ctx, fs, {0, 2 * numel}, {1, 3 * numel}, {});
auto fs3 = slice(ctx, fs, {0, 3 * numel}, {1, 4 * numel}, {});
// calculate result
auto s01 = _add(ctx, fs0, fs1);
auto s23 = _add(ctx, fs2, fs3);
auto r = _add(ctx, s01, s23);
auto res = _sub(ctx, reshape(ctx, r, x.shape()), k1);
return res;
}
// Generate perm by bit vector
// input: bit vector generated by bit decomposition
// output: shared inverse permutation
//
// Example:
// 1) x = [1, 0, 1, 0, 0]
// 2) rev_x = [0, 1, 0, 1, 1]
// 3) f = [rev_x, x]
// f = [0, 1, 0, 1, 1, 1, 0, 1, 0, 0]
// 4) s[i] = s[i - 1] + f[i], s[0] = f[0]
// s = [0, 1, 1, 2, 3, 4, 4, 5, 5, 5]
// 5) fs = f * s
// fs = [0, 1, 0, 2, 3, 4, 0, 5, 0, 0]
// 6) split fs to two vector
// fsv[0] = [0, 1, 0, 2, 3]
// fsv[1] = [4, 0, 5, 0, 0]
// 7) r = fsv[0] + fsv[1]
// r = [4, 1, 5, 2, 3]
// 8) get res by sub r by one
// res = [3, 0, 4, 1, 2]
spu::Value _gen_inv_perm_by_bv(SPUContext *ctx, const spu::Value &x) {
SPU_ENFORCE(x.shape().ndim() == 1, "x should be 1-d");
const auto k1 = _constant(ctx, 1U, x.shape());
auto rev_x = _sub(ctx, k1, x);
const auto numel = x.numel();
auto f = concatenate(ctx, {unsqueeze(ctx, rev_x), unsqueeze(ctx, x)}, 1);
// calculate prefix sum
auto ps = _prefix_sum(ctx, f);
// mul f and s
auto fs = _mul(ctx, f, ps);
auto fs0 = slice(ctx, fs, {0, 0}, {1, numel}, {});
auto fs1 = slice(ctx, fs, {0, numel}, {1, 2 * numel}, {});
// calculate result
auto r = _add(ctx, fs0, fs1);
auto res = _sub(ctx, reshape(ctx, r, x.shape()), k1);
return res;
}
// Ref: https://eprint.iacr.org/2019/695.pdf
// Algorithm 14: Optimized composition of two permutations
//
// Compose is actually a special case of apply_perm where both inputs are
// permutations.
//
// The input is a shared inverse permutation <perm>, a public permutation
// shuffled_perm generated by _opt_apply_inv_perm_ss, and a secret permutation
// share random_perm for secure unshuffle.
//
// The steps are as follows:
// 1) permute <perm> by shuffled_perm as <sm>
// 2) secure unshuffle <sm> and return results
spu::Value _opt_apply_perm_ss(SPUContext *ctx, const spu::Value &perm,
const spu::Value &shuffled_perm,
const spu::Value &random_perm) {
auto sm = hal::_perm_sp(ctx, perm, shuffled_perm);
// this is actually shuffle
auto res = hal::_inv_perm_ss(ctx, sm, random_perm);
return res;
}
std::vector<spu::Value> _bit_decompose(SPUContext *ctx, const spu::Value &x,
int64_t valid_bits) {
auto x_bshare = _prefer_b(ctx, x);
size_t nbits = valid_bits != -1
? static_cast<size_t>(valid_bits)
: x_bshare.storage_type().as<BShare>()->nbits();
_hint_nbits(x_bshare, nbits);
if (ctx->hasKernel("b2a_disassemble")) {
auto ret =
dynDispatch<std::vector<spu::Value>>(ctx, "b2a_disassemble", x_bshare);
return ret;
}
const auto k1 = _constant(ctx, 1U, x.shape());
std::vector<spu::Value> rets_b;
rets_b.reserve(nbits);
for (size_t bit = 0; bit < nbits; ++bit) {
auto x_bshare_shift =
right_shift_logical(ctx, x_bshare, {static_cast<int64_t>(bit)});
rets_b.push_back(_and(ctx, x_bshare_shift, k1));
}
std::vector<spu::Value> rets_a;
vmap(rets_b.begin(), rets_b.end(), std::back_inserter(rets_a),
[&](const Value &x) { return _prefer_a(ctx, x); });
return rets_a;
}
// Generate vector of bit decomposition of sorting keys
std::vector<spu::Value> _gen_bv_vector(SPUContext *ctx,
absl::Span<spu::Value const> keys,
SortDirection direction,
int64_t valid_bits) {
std::vector<spu::Value> ret;
const auto k1 = _constant(ctx, 1U, keys[0].shape());
const bool is_descending = (direction == SortDirection::Descending);
// keys[0] is the most significant key
for (size_t i = keys.size(); i > 0; --i) {
const auto t = _bit_decompose(ctx, keys[i - 1], valid_bits);
const bool is_unsigned = keys[i - 1].isUInt();
SPU_ENFORCE(t.size() > 0);
// Process non-sign bits (same logic for both signed and unsigned types)
// Radix sort is a stable sorting algorithm for the ascending order, if