-
Notifications
You must be signed in to change notification settings - Fork 121
/
fixedpoint_tensor_imp.h
1814 lines (1491 loc) · 64.2 KB
/
fixedpoint_tensor_imp.h
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 (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// 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.
#pragma once
#include <memory>
#include <algorithm>
#include "paddle/fluid/platform/enforce.h"
namespace aby3 {
template<typename T, size_t N>
FixedPointTensor<T, N>::FixedPointTensor(TensorAdapter<T>* share_tensor[2]) {
// TODO: check tensors' shapes
_share[0] = share_tensor[0];
_share[1] = share_tensor[1];
}
template<typename T, size_t N>
FixedPointTensor<T, N>::FixedPointTensor(TensorAdapter<T>* share_tensor_0,
TensorAdapter<T>* share_tensor_1) {
// TODO: check tensors' shapes
_share[0] = share_tensor_0;
_share[1] = share_tensor_1;
}
template<typename T, size_t N>
TensorAdapter<T>* FixedPointTensor<T, N>::mutable_share(size_t idx) {
PADDLE_ENFORCE_LT(idx, 2, "Input should be less than 2.");
return _share[idx];
}
template<typename T, size_t N>
const TensorAdapter<T>* FixedPointTensor<T, N>::share(size_t idx) const {
PADDLE_ENFORCE_LT(idx, 2, "Input should be less than 2.");
return _share[idx];
}
// reveal fixedpointtensor to one party
template<typename T, size_t N>
void FixedPointTensor<T, N>::reveal_to_one(size_t party,
TensorAdapter<T>* ret) const {
if (party == this->party()) {
// TODO: check if tensor shape equal
auto buffer = tensor_factory()->template create<T>(ret->shape());
aby3_ctx()->network()->template recv(pre_party(), *buffer);
share(0)->add(buffer.get(), ret);
share(1)->add(ret, ret);
ret->scaling_factor() = N;
} else if (party == next_party()) {
aby3_ctx()->network()->template send(party, *share(0));
}
}
// reveal fixedpointtensor to all parties
template<typename T, size_t N>
void FixedPointTensor<T, N>::reveal(TensorAdapter<T>* ret) const {
for (size_t i = 0; i < 3; ++i) {
reveal_to_one(i, ret);
}
}
template<typename T, size_t N>
const std::vector<size_t> FixedPointTensor<T, N>::shape() const {
return _share[0]->shape();
}
//convert TensorAdapter to shares
template<typename T, size_t N>
void FixedPointTensor<T, N>::share(const TensorAdapter<T>* input,
TensorAdapter<T>* output_shares[3],
block seed) {
if (equals(seed, g_zero_block)) {
seed = block_from_dev_urandom();
}
//set seed of prng[2]
aby3_ctx()->set_random_seed(seed, 2);
aby3_ctx()->template gen_random_private(*output_shares[0]);
aby3_ctx()->template gen_random_private(*output_shares[1]);
auto temp = tensor_factory()->template create<T>(input->shape());
output_shares[0]->add(output_shares[1], temp.get());
input->sub(temp.get(), output_shares[2]);
for (int i = 0; i < 3; ++i) {
output_shares[i]->scaling_factor() = input->scaling_factor();
}
}
//convert TensorAdapter to shares and distribute to all parties
template<typename T, size_t N>
void FixedPointTensor<T, N>::online_share(const size_t party,
const TensorAdapter<T>* input,
FixedPointTensor<T, N>* ret) {
// create a tensor which contains two shares to send/recv
auto shape = input->shape();
std::vector<size_t> shape_ = shape;
shape_.insert(shape_.begin(), 2);
auto one_party_shares = tensor_factory()->template create<T>(shape_);
if (party == FixedPointTensor::party()) {
// this party has original data:
// encrypt input into 3 shares
auto temp = tensor_factory()->template malloc_tensor<T>(3, input->shape());
TensorAdapter<T>* shares[3]{temp[0].get(), temp[1].get(), temp[2].get()};
share(input, shares);
// share 0&1
shares[0]->copy(ret->_share[0]);
shares[1]->copy(ret->_share[1]);
#ifdef __NVCC__
// send share 1&2 to next_party
auto one_party_shares_ = tensor_factory()->template create<T>(shape_);
cudaMemcpy(one_party_shares.get()->data(), shares[1]->data(),
shares[1]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
cudaMemcpy(one_party_shares.get()->data() + shares[1]->numel(), shares[2]->data(),
shares[2]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
// send share 2&0 to pre_party
cudaMemcpy(one_party_shares_.get()->data(), shares[2]->data(),
shares[2]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
cudaMemcpy(one_party_shares_.get()->data() + shares[2]->numel(), shares[0]->data(),
shares[0]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
NCCL_GROUP_START
aby3_ctx()->network()->template send(next_party(), *one_party_shares);
aby3_ctx()->network()->template send(pre_party(), *one_party_shares_);
NCCL_GROUP_START
#else // __NVCC__
// send share 1&2 to next_party
std::copy(shares[1]->data(), shares[1]->data() + shares[1]->numel(),
one_party_shares.get()->data());
std::copy(shares[2]->data(), shares[2]->data() + shares[2]->numel(),
one_party_shares.get()->data() + shares[1]->numel());
aby3_ctx()->network()->template send(next_party(), *one_party_shares);
// send share 2&0 to pre_party
std::copy(shares[2]->data(), shares[2]->data() + shares[2]->numel(),
one_party_shares.get()->data());
std::copy(shares[0]->data(), shares[0]->data() + shares[0]->numel(),
one_party_shares.get()->data() + shares[2]->numel());
aby3_ctx()->network()->template send(pre_party(), *one_party_shares);
#endif // __NVCC__
} else {
// recv share from 'party' who has original data
aby3_ctx()->network()->template recv(party, *(one_party_shares));
#ifdef __NVCC__
cudaMemcpy(ret->_share[0]->data(), one_party_shares.get()->data(),
ret->_share[0]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
cudaMemcpy(ret->_share[1]->data(), one_party_shares.get()->data() + ret->_share[0]->numel(),
ret->_share[1]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
#else // __NVCC__
std::copy(one_party_shares->data(), one_party_shares->data() + one_party_shares->numel() / 2,
ret->_share[0]->data());
std::copy(one_party_shares->data() + one_party_shares->numel() / 2,
one_party_shares->data() + one_party_shares->numel(),
ret->_share[1]->data());
#endif // __NVCC__
}
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::add(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret) const {
_share[0]->add(rhs->_share[0], ret->_share[0]);
_share[1]->add(rhs->_share[1], ret->_share[1]);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::add(const TensorAdapter<T>* rhs,
FixedPointTensor<T, N>* ret) const {
PADDLE_ENFORCE_EQ(N, rhs->scaling_factor(),
"no match scaling factor");
if (party() == 0) {
_share[0]->add(rhs, ret->_share[0]);
_share[1]->copy(ret->_share[1]);
} else if (party() == 1) {
_share[0]->copy(ret->_share[0]);
_share[1]->copy(ret->_share[1]);
} else {
_share[0]->copy(ret->_share[0]);
_share[1]->add(rhs, ret->_share[1]);
}
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::sub(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret) const {
_share[0]->sub(rhs->_share[0], ret->_share[0]);
_share[1]->sub(rhs->_share[1], ret->_share[1]);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::sub(const TensorAdapter<T>* rhs,
FixedPointTensor<T, N>* ret) const {
PADDLE_ENFORCE_EQ(N, rhs->scaling_factor(),
"no match scaling factor");
if (party() == 0) {
_share[0]->sub(rhs, ret->_share[0]);
_share[1]->copy(ret->_share[1]);
} else if (party() == 1) {
_share[0]->copy(ret->_share[0]);
_share[1]->copy(ret->_share[1]);
} else {
_share[0]->copy(ret->_share[0]);
_share[1]->sub(rhs, ret->_share[1]);
}
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::negative(FixedPointTensor<T, N>* ret) const {
_share[0]->negative(ret->_share[0]);
_share[1]->negative(ret->_share[1]);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::mul(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret) const {
mul_trunc(this, rhs, ret, [](
const TensorAdapter<T>* lhs,
const TensorAdapter<T>* rhs,
TensorAdapter<T>* ret) {
lhs->mul(rhs, ret);
});
}
#ifdef USE_ABY3_TRUNC1 //use aby3 trunc1
template<typename T, size_t N>
void FixedPointTensor<T, N>::truncate(const FixedPointTensor<T, N>* op,
FixedPointTensor<T, N>* ret,
size_t scaling_factor) {
if (scaling_factor == 0) {
op->share(0)->copy(ret->mutable_share(0));
op->share(1)->copy(ret->mutable_share(1));
}
// implement ABY3's truncate1 algorithm
if (party() == 0) {
// party0
op->_share[0]->rshift(scaling_factor, ret->_share[0]);
aby3_ctx()->network()->template recv(1, *(ret->_share[1]));
} else if (party() == 1) {
// party1
auto r_12 = tensor_factory()->template create<T>(op->shape());
aby3_ctx()->template gen_random(*r_12.get(), true);
op->_share[0]->add(op->_share[1], ret->_share[0]);
// trunc from [SecureML, Thm.1]
ret->_share[0]->negative(ret->_share[0]);
ret->_share[0]->rshift(scaling_factor, ret->_share[0]);
ret->_share[0]->negative(ret->_share[0]);
ret->_share[0]->sub(r_12.get(), ret->_share[0]);
aby3_ctx()->network()->template send(0, *(ret->_share[0]));
r_12->copy(ret->_share[1]);
} else {
// party2
op->_share[1]->rshift(scaling_factor, ret->_share[1]);
auto r_21 = tensor_factory()->template create<T>(op->shape());
aby3_ctx()->template gen_random(*r_21.get(), false);
r_21->copy(ret->_share[0]);
}
return;
}
#else // use truncate3
// Protocol. `truncate3` (illustrated for data type T = int64_t)
// motivation:
// truncates in aby3 may cause msb error with small probability
// the reason is that before rishft op, its masked value e.g., x' - r' may overflow in int64_t
// so that, in `truncate3`, we limit r' in (-2^62, 2^62) to avoid the problem.
// notice:
// when r' is contrainted in (-2^62, 2^62),
// the SD (statistical distance) of x' - r' between this
// and r' in Z_{2^64} is equal to |X| / (2^63 + |X|)
// detail protocol:
// Input: P0 (x0', x1'), P1 (x1', x2'), P2 (x2', x0')
// P2: 1. gen r' randomly from [-2^(l-2), 2^(l-2)]
// 2. gen r0 using preshared seed with P0
// 3. gen r1 randomly
// 4. compute r2=r'/2^N - r0 - r1
// 5. x2 := r1 + r2, x0 := r0
// P2->>P0: x2' - r'
// P2->>P1: x0' - r', x2
// P0: 1. x0 := r0
// 2. x1 := (x2' - r' + x0' + x1')/2^N
// P1: 1. x1 := (x0' - r' + x1' + x2')/2^N
// 2. x2:= x2
template<typename T, size_t N>
void FixedPointTensor<T, N>::truncate(const FixedPointTensor<T, N>* op,
FixedPointTensor<T, N>* ret,
size_t scaling_factor) {
if (scaling_factor == 0) {
op->share(0)->copy(ret->mutable_share(0));
op->share(1)->copy(ret->mutable_share(1));
return;
}
std::vector<std::shared_ptr<TensorAdapter<T>>> temp;
if (party() == 2) {
for (int i = 0; i < 6; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>(op->shape()));
}
// r'
aby3_ctx()->template gen_random_private(*temp[0]);
temp[0]->rshift(1, temp[0].get());
// r
temp[0]->rshift(scaling_factor, temp[1].get());
// r_0
aby3_ctx()->template gen_random(*temp[2], true);
// r_1
aby3_ctx()->template gen_random_private(*temp[3]);
// r_2
temp[1]->sub(temp[2].get(), temp[1].get());
temp[1]->sub(temp[3].get(), temp[1].get());
// x0' - r'
op->share(1)->sub(temp[0].get(), temp[4].get());
// x2' - r'
op->share(0)->sub(temp[0].get(), temp[0].get());
// x_2 = r_2 + r_1
temp[1]->add(temp[3].get(), temp[1].get());
auto shape_ = op->shape();
shape_.insert(shape_.begin(), 2);
temp[5]->reshape(shape_);
// merge msg to save send
#ifdef __NVCC__
cudaMemcpy(temp[5]->data(), temp[1]->data(),
temp[1]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
cudaMemcpy(temp[5]->data() + temp[1]->numel(), temp[4]->data(),
temp[4]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
#else // __NVCC__
std::copy(temp[1]->data(), temp[1]->data() + temp[1]->numel(),
temp[5]->data());
std::copy(temp[4]->data(), temp[4]->data() + temp[4]->numel(),
temp[5]->data() + temp[1]->numel());
#endif // __NVCC__
NCCL_GROUP_START
// send x_2, x0' - r' to P1
aby3_ctx()->network()->template send(1, *temp[5]);
// send x2' - r' to P0
aby3_ctx()->network()->template send(0, *temp[0]);
NCCL_GROUP_END
temp[1]->copy(ret->mutable_share(0));
temp[2]->copy(ret->mutable_share(1));
} else if (party() == 1) {
for (int i = 0; i < 4; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>(op->shape()));
}
auto shape_ = op->shape();
shape_.insert(shape_.begin(), 2);
temp[3]->reshape(shape_);
// recv x_2, x'_0 - r'
NCCL_GROUP_START
aby3_ctx()->network()->template recv(2, *temp[3]);
NCCL_GROUP_END
#ifdef __NVCC__
cudaMemcpy(temp[0]->data(), temp[3]->data(),
temp[0]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
cudaMemcpy(temp[1]->data(), temp[3]->data() + temp[0]->numel(),
temp[1]->numel() * sizeof(T),cudaMemcpyDeviceToDevice);
#else // __NVCC__
std::copy(temp[3]->data(), temp[3]->data() + temp[0]->numel(),
temp[0]->data());
std::copy(temp[3]->data() + temp[0]->numel(),
temp[3]->data() + temp[0]->numel() + temp[1]->numel(),
temp[1]->data());
#endif // __NVCC__
// P1 reveals x' - r'
op->share(0)->add(op->share(1), temp[2].get());
temp[2]->add(temp[1].get(), temp[2].get());
// truncate x'-r'
temp[2]->rshift(scaling_factor, temp[2].get());
temp[2]->copy(ret->mutable_share(0));
temp[0]->copy(ret->mutable_share(1));
} else { // party == 0
for (int i = 0; i < 2; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>(op->shape()));
}
// recv x'_2 - r'
NCCL_GROUP_START
aby3_ctx()->network()->template recv(2, *temp[0]);
NCCL_GROUP_END
// P0 reveals x' - r'
op->share(0)->add(op->share(1), temp[1].get());
temp[1]->add(temp[0].get(), temp[0].get());
// truncate x'-r'
temp[0]->rshift(scaling_factor, temp[0].get());
// x_1
temp[0]->copy(ret->mutable_share(1));
// x_0 = r_0
aby3_ctx()->template gen_random(*ret->mutable_share(0), false);
}
// compensation for carry in
auto tensor_carry_in = tensor_factory()->template create<T>(ret->shape());
assign_to_tensor(tensor_carry_in.get(), (T)1);
tensor_carry_in->scaling_factor() = N;
ret->add(tensor_carry_in.get(), ret);
}
#endif //USE_ABY3_TRUNC1
template<typename T, size_t N>
template<typename MulFunc>
void FixedPointTensor<T, N>::mul_trunc(const FixedPointTensor<T, N>* lhs,
const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret,
MulFunc mul_func) {
auto r_zero = tensor_factory()->template create<T>(ret->shape());
aby3_ctx()->gen_zero_sharing_arithmetic(*r_zero.get());
// temp = _share[0]->mul(rhs->_share[0]) +
// _share[0]->mul(rhs->_share[1]) +
// _share[1]->mul(rhs->_share[0]) +
// r_zero
auto temp = tensor_factory()->template create<T>(ret->shape());
auto temp1 = tensor_factory()->template create<T>(ret->shape());
// use mul_func to fit both element_wise mul and mat mul
mul_func(lhs->share(0), rhs->share(0), temp.get());
mul_func(lhs->share(0), rhs->share(1), temp1.get());
temp1->add(temp.get(), temp1.get());
mul_func(lhs->share(1), rhs->share(0), temp.get());
temp1->add(r_zero.get(), temp1.get());
temp->add(temp1.get(), temp.get());
auto temp2 = tensor_factory()->template create<T>(ret->shape());
auto temp3 = tensor_factory()->template create<T>(ret->shape());
TensorAdapter<int64_t>* temp_array[2] = {temp2.get(), temp3.get()};
std::shared_ptr<FixedPointTensor<T, N>> ret_no_trunc =
std::make_shared<FixedPointTensor<T, N>>(temp_array);
temp->copy(ret_no_trunc->_share[0]);
reshare(temp.get(), ret_no_trunc->_share[1]);
truncate(ret_no_trunc.get(), ret, N);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::mul(const TensorAdapter<T>* rhs,
FixedPointTensor<T, N>* ret) const {
// PADDLE_ENFORCE_EQ(N, rhs->scaling_factor(),
// "no match scaling factor");
auto temp0 = tensor_factory()->template create<T>(this->shape());
auto temp1 = tensor_factory()->template create<T>(this->shape());
std::shared_ptr<FixedPointTensor<T, N>> temp =
std::make_shared<FixedPointTensor<T, N>>(temp0.get(), temp1.get());
_share[0]->mul(rhs, temp->_share[0]);
_share[1]->mul(rhs, temp->_share[1]);
truncate(temp.get(), ret, rhs->scaling_factor());
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::sum(FixedPointTensor<T, N>* ret) const {
PADDLE_ENFORCE_EQ(ret->numel(), 1, "output size should be 1.");
_share[0]->sum(ret->mutable_share(0));
_share[1]->sum(ret->mutable_share(1));
}
template<typename T, size_t N>
template<template<typename U, size_t...> class CTensor,
size_t... N1>
void FixedPointTensor<T, N>::dot_mul(const CTensor<T, N1...>* rhs,
FixedPointTensor<T, N>* ret) const {
PADDLE_ENFORCE_EQ(ret->numel(), 1, "output size should be 1.");
auto temp0 = tensor_factory()->template create<T>(this->shape());
auto temp1 = tensor_factory()->template create<T>(this->shape());
std::shared_ptr<FixedPointTensor<T, N>> temp =
std::make_shared<FixedPointTensor<T, N>>(temp0.get(), temp1.get());
this->mul(rhs, temp.get());
temp->sum(ret);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::dot_mul(const TensorAdapter<T>* rhs, FixedPointTensor* ret) const {
PADDLE_ENFORCE_EQ(ret->numel(), 1, "output size should be 1.");
auto temp0 = tensor_factory()->template create<T>(this->shape());
auto temp1 = tensor_factory()->template create<T>(this->shape());
std::shared_ptr<FixedPointTensor<T, N>> temp =
std::make_shared<FixedPointTensor<T, N>>(temp0.get(), temp1.get());
this->mul(rhs, temp.get());
temp->sum(ret);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::mat_mul(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret,
bool trans_lhs,
bool trans_rhs,
bool sum_reduce_batch) const {
mul_trunc(this, rhs, ret, [trans_lhs, trans_rhs, sum_reduce_batch](
const TensorAdapter<T>* lhs,
const TensorAdapter<T>* rhs,
TensorAdapter<T>* ret) {
lhs->mat_mul(rhs, ret, trans_lhs, trans_rhs, sum_reduce_batch);
});
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::mat_mul(const TensorAdapter<T>* rhs,
FixedPointTensor<T, N>* ret,
bool trans_lhs,
bool trans_rhs,
bool sum_reduce_batch) const {
_share[0]->mat_mul(rhs, ret->_share[0], trans_lhs, trans_rhs, sum_reduce_batch);
_share[1]->mat_mul(rhs, ret->_share[1], trans_lhs, trans_rhs, sum_reduce_batch);
truncate(ret, ret, rhs->scaling_factor());
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::div(const TensorAdapter<T>* rhs,
FixedPointTensor<T, N>* ret) const {
PADDLE_ENFORCE_EQ(N, rhs->scaling_factor(),
"no match scaling factor");
double scale = std::pow(2, rhs->scaling_factor());
auto temp = tensor_factory()->template create<T>(this->shape());
auto temp2 = tensor_factory()->template create<T>(this->shape());
assign_to_tensor(temp.get(), (T)(scale * scale));
temp->scaling_factor() = rhs->scaling_factor();
temp2->scaling_factor() = rhs->scaling_factor();
temp->div(rhs, temp2.get());
this->mul(temp2.get(), ret);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::div(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret,
size_t iter, double x0) const {
auto temp0 = tensor_factory()->template create<T>(ret->shape());
auto temp1 = tensor_factory()->template create<T>(ret->shape());
std::shared_ptr<FixedPointTensor<T, N>> temp =
std::make_shared<FixedPointTensor<T, N>>(temp0.get(), temp1.get());
reciprocal(rhs, temp.get(), iter, x0);
this->mul(temp.get(), ret);
}
template<typename T, size_t N>
void FixedPointTensor<T, N>::exp(FixedPointTensor<T, N>* ret,
size_t iter) const {
// exp approximate: exp(x) = \lim_{n->inf} (1+x/n)^n
// where n = 2^ite
auto pow_iter = tensor_factory()->template create<T>(this->shape());
assign_to_tensor(pow_iter.get(), (T) (pow(2, N -iter)));
pow_iter->scaling_factor() = N;
auto tensor_one = tensor_factory()->template create<T>(this->shape());
assign_to_tensor(tensor_one.get(), (T) 1 << N);
tensor_one->scaling_factor() = N;
this->mul(pow_iter.get(), ret);
ret->add(tensor_one.get(), ret);
for (int i = 0; i < iter; ++i) {
ret->mul(ret, ret);
}
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::relu(FixedPointTensor<T, N>* ret) const {
//utilize polynomial_piecewise
// break_point = {0}, coeff[0] = {0, 0}, coeff[1] = {0, 1}
// break_point.shape = {1, this->shape}, coeff.shape = {2, 2, this->shape}
auto shape_ = shape();
//construct break_point
auto b_shape = shape_;
b_shape.insert(b_shape.begin(), 1);
auto break_point = tensor_factory()->template create<T>(b_shape);
assign_to_tensor(break_point.get(), (T)0);
break_point->scaling_factor() = N;
//contruct coeff
std::vector<size_t> c_shape = {4, 1};
c_shape.insert(c_shape.end(), shape_.begin(), shape_.end());
auto coeff = tensor_factory()->template create<T>(c_shape);
auto slice = tensor_factory()->template create<T>();
coeff->slice(0, 3, slice.get());
assign_to_tensor(slice.get(), (T)0);
coeff->slice(3, 4, slice.get());
assign_to_tensor(slice.get(), (T) 1 << N);
c_shape[0] = 2;
c_shape[1] = 2;
coeff->reshape(c_shape);
coeff->scaling_factor() = N;
this->polynomial_piecewise(coeff.get(), break_point.get(), ret);
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::relu_with_derivative(
FixedPointTensor<T, N>* ret, BooleanTensor<T>* derivative) const {
auto shape_ = shape();
auto zero = tensor_factory()->template create<T>(shape_);
assign_to_tensor(zero.get(), (T)0);
zero->scaling_factor() = N;
auto tmp0 = tensor_factory()->template create<T>(shape_);
auto tmp1 = tensor_factory()->template create<T>(shape_);
BooleanTensor<T> der(tmp0.get(), tmp1.get());
gt(zero.get(), &der);
der.mul(this, ret);
if (derivative) {
der.share(0)->copy(derivative->share(0));
der.share(1)->copy(derivative->share(1));
}
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::sigmoid_chebyshev(FixedPointTensor<T, N>* ret) const {
//utilize Chebyshev polynomial approximation
// more accurate in small range, such as [-4, 4]
auto shape = ret->shape();
std::vector<size_t> shape_ = shape;
shape_.insert(shape_.begin(), 10);
auto numel = ret->numel();
auto coeff = tensor_factory()->template create<T>(shape_);
std::vector<double> w;
w.resize(10, 0.0f);
w[0] = 0.5;
w[1] = 0.2159198015;
w[3] = -0.0082176259;
w[5] = 0.0001825597;
w[7] = -0.0000018848;
w[9] = 0.0000000072;
double scale = pow(2, N);
auto slice = tensor_factory()->template create<T>();
for (int i = 0; i < 10; ++i) {
coeff->slice(i, i + 1, slice.get());
assign_to_tensor(slice.get(), (T) (w[i] * scale));
}
coeff->scaling_factor() = N;
polynomial(coeff.get(), ret);
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::sigmoid(FixedPointTensor<T, N>* ret) const {
//utilize polynomial_piecewise
// break_point = {-2.5, 2.5}
// coeff[0] = {10^-4, 0}, coeff[1] = {0.5, 0.17}
// coeff[2] = {1 - 10^-4, 0}
// break_point.shape = {2, this->shape}, coeff.shape = {3, 2, this->shape}
//construct break_point
auto shape_ = shape();
//construct break_point
auto b_shape = shape_;
b_shape.insert(b_shape.begin(), 2);
auto break_point = tensor_factory()->template create<T>(b_shape);
auto slice = tensor_factory()->template create<T>();
break_point->slice(0, 1, slice.get());
assign_to_tensor(slice.get(), (T) (-2.5 * pow(2, N)));
break_point->slice(1, 2, slice.get());
assign_to_tensor(slice.get(), (T) (2.5 * pow(2, N)));
break_point->scaling_factor() = N;
//contruct coeff
std::vector<size_t> c_shape = {6, 1};
c_shape.insert(c_shape.end(), shape_.begin(), shape_.end());
auto coeff = tensor_factory()->template create<T>(c_shape);
double scale = std::pow(2, N);
coeff->slice(0, 1, slice.get());
assign_to_tensor(slice.get(), (T) (0.0001 * scale));
coeff->slice(1, 2, slice.get());
assign_to_tensor(slice.get(), (T) (0));
coeff->slice(2, 3, slice.get());
assign_to_tensor(slice.get(), (T) (0.5 * scale));
coeff->slice(3, 4, slice.get());
assign_to_tensor(slice.get(), (T) (0.17 * scale));
coeff->slice(4, 5, slice.get());
assign_to_tensor(slice.get(), (T) ((1 - 0.0001) * scale));
coeff->slice(5, 6, slice.get());
assign_to_tensor(slice.get(), (T) (0));
c_shape[0] = 3;
c_shape[1] = 2;
coeff->reshape(c_shape);
coeff->scaling_factor() = N;
this->polynomial_piecewise(coeff.get(), break_point.get(), ret);
}
// sigmoid(x) = 1 / (1 + exp(-x))
template< typename T, size_t N>
void FixedPointTensor<T, N>::sigmoid_high_precision(FixedPointTensor<T, N>* ret) const {
std::vector<std::shared_ptr<TensorAdapter<T>>> temp;
for (int i = 0; i < 2; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>(ret->shape()));
}
auto tensor_one_share0 = tensor_factory()->template create<T>(shape());
auto tensor_one_share1 = tensor_factory()->template create<T>(shape());
auto tensor_one = tensor_factory()->template create<T>(shape());
assign_to_tensor(tensor_one.get(), (T) (1.0 * pow(2, N)));
tensor_one->scaling_factor() = N;
assign_to_tensor(tensor_one_share0.get(), (T) (1.0 * pow(2, N) / 3.0));
assign_to_tensor(tensor_one_share1.get(), (T) (1.0 * pow(2, N) / 3.0));
FixedPointTensor tensor_one_ft(tensor_one_share0.get(), tensor_one_share1.get());
FixedPointTensor out(temp[0].get(), temp[1].get());
this->negative(&out);
out.exp(&out);
out.add(tensor_one.get(), &out);
tensor_one_ft.long_div(&out, ret);
}
template< typename T, size_t N>
void FixedPointTensor<T, N>::sigmoid_enhanced(FixedPointTensor<T, N>* ret) const {
//utilize polynomial_piecewise
// break_point = {-5, -2.5, 2.5, 5}
// coeff[0] = {10^-4, 0}, coeff[1] = {0.145, 0.02776}
// coeff[2] = {0.5, 0.17}, coeff[3] = {0.85498, 0.02776}, coeff[4] = {0.9999, 0}
// break_point.shape = {4, this->shape}, coeff.shape = {5, 2, this->shape}
//construct break_point
auto shape_ = shape();
//construct break_point
auto b_shape = shape_;
b_shape.insert(b_shape.begin(), 4);
auto break_point = tensor_factory()->template create<T>(b_shape);
double scale = pow(2, N);
double bp_[4] = {-5, -2.5, 2.5, 5};
auto slice = tensor_factory()->template create<T>();
for (int i = 0; i < 4; ++i) {
break_point->slice(i, i + 1, slice.get());
assign_to_tensor(slice.get(), (T) (bp_[i] * scale));
}
break_point->scaling_factor() = N;
double w_[10] = {0.0001, 0, 0.145, 0.02776, 0.5, 0.17, 0.85498, 0.02776 ,0.9999, 0};
//contruct coeff
std::vector<size_t> c_shape = {10, 1};
c_shape.insert(c_shape.end(), shape_.begin(), shape_.end());
auto coeff = tensor_factory()->template create<T>(c_shape);
for (int i = 0; i < 10; ++i) {
coeff->slice(i, i + 1, slice.get());
assign_to_tensor(slice.get(), (T) (w_[i] * scale));
}
c_shape[0] = 5;
c_shape[1] = 2;
coeff->reshape(c_shape);
coeff->scaling_factor() = N;
this->polynomial_piecewise(coeff.get(), break_point.get(), ret);
}
#ifndef USE_CUDA
template< typename T, size_t N>
void FixedPointTensor<T, N>::softmax(FixedPointTensor<T, N>* ret,
bool use_relu, bool use_long_div) const {
// softmax axis = -1
const size_t col = *(shape().end() - 1);
const size_t row = numel() / col;
std::vector<std::shared_ptr<TensorAdapter<T>>> temp;
// 11 for allocating temp tensor
for (size_t i = 0; i < 11; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>());
}
temp[0]->reshape({row, col});
temp[1]->reshape({row, col});
FixedPointTensor<T, N> x(temp[0].get(), temp[1].get());
if (!use_relu) {
temp[2]->reshape({col, row});
temp[3]->reshape({col, row});
temp[4]->reshape({1, row});
temp[5]->reshape({1, row});
}
FixedPointTensor<T, N> x_t(temp[2].get(), temp[3].get());
FixedPointTensor<T, N> max_x_t(temp[4].get(), temp[5].get());
temp[6]->reshape({row, 1});
temp[7]->reshape({row, 1});
FixedPointTensor<T, N> max_x(temp[6].get(), temp[7].get());
temp[8]->reshape({row, col});
temp[9]->reshape({row, col});
FixedPointTensor<T, N> max_x_broadcast(temp[8].get(), temp[9].get());
temp[10]->reshape({row, col});
auto exp_lower_bound = temp[10].get();
auto transpose = [](const TensorAdapter<T>* in, TensorAdapter<T>* out) {
std::vector<int> axis{ 1, 0 };
// suppose input dims = 2
dynamic_cast<const common::PaddleTensor<T>*>(in)->template Transpose<2>(axis, out);
};
auto broadcast = [](const TensorAdapter<T>* in, TensorAdapter<T>* out) {
// suppose input dims = 2
const size_t col = out->shape()[1];
std::vector<int> axis{ 1, col };
dynamic_cast<const common::PaddleTensor<T>*>(in)->template Broadcast<2>(axis, out);
};
share(0)->copy(x.mutable_share(0));
share(1)->copy(x.mutable_share(1));
if (use_relu) {
x.relu(&x);
} else { // use exp
transpose(x.share(0), x_t.mutable_share(0));
transpose(x.share(1), x_t.mutable_share(1));
// x = max(input - max(input), exp_lower_bound)
x_t.max_pooling(&max_x_t);
transpose(max_x_t.share(0), max_x.mutable_share(0));
transpose(max_x_t.share(1), max_x.mutable_share(1));
broadcast(max_x.share(0), max_x_broadcast.mutable_share(0));
broadcast(max_x.share(1), max_x_broadcast.mutable_share(1));
x.sub(&max_x_broadcast, &x);
// n = 64, see exp
assign_to_tensor(exp_lower_bound, (T)(-64 * (1 << N)));
exp_lower_bound->scaling_factor() = N;
x.sub(exp_lower_bound, &x);
x.relu(&x);
x.add(exp_lower_bound, &x);
x.exp(&x);
}
// reuse max_x as sum
reduce(&x, &max_x);
if (!use_long_div) { // invert sum by Newton's method
// divisor range = [1/col, 1.0]
// TODO: find better iter num & init val
reciprocal(&max_x, &max_x, 16, 0.5 / col);
}
broadcast(max_x.share(0), max_x_broadcast.mutable_share(0));
broadcast(max_x.share(1), max_x_broadcast.mutable_share(1));
if (use_long_div) {
x.long_div(&max_x_broadcast, &x, 1);
} else {
x.mul(&max_x_broadcast, &x);
}
x.share(0)->copy(ret->mutable_share(0));
x.share(1)->copy(ret->mutable_share(1));
}
#endif // USE_CUDA
template<typename T, size_t N>
void FixedPointTensor<T, N>::long_div(const FixedPointTensor<T, N>* rhs,
FixedPointTensor<T, N>* ret,
size_t int_len) const {
std::vector<std::shared_ptr<TensorAdapter<T>>> temp;
for (int i = 0; i < 16; ++i) {
temp.emplace_back(
tensor_factory()->template create<T>(ret->shape()));
}
BooleanTensor<T> sign_lhs(temp[0].get(), temp[1].get());
BooleanTensor<T> sign_rhs(temp[2].get(), temp[3].get());
BooleanTensor<T> sign_ret(temp[4].get(), temp[5].get());
FixedPointTensor<T, N> abs_lhs(temp[6].get(), temp[7].get());
FixedPointTensor<T, N> abs_rhs(temp[8].get(), temp[9].get());
FixedPointTensor<T, N> sub_rhs(temp[10].get(), temp[11].get());
BooleanTensor<T> cmp_res(temp[12].get(), temp[13].get());
BooleanTensor<T> cmp_res_all(temp[14].get(), temp[15].get());
assign_to_tensor(cmp_res_all.share(0), (T)0);
assign_to_tensor(cmp_res_all.share(1), (T)0);
const size_t msb = sizeof(T) * 8 - 1;
sign_lhs.bit_extract(msb, this);
sign_rhs.bit_extract(msb, rhs);
sign_lhs.bitwise_xor(&sign_rhs, &sign_ret);
auto lshift = [] (const FixedPointTensor<T, N>* in,
size_t rhs,
FixedPointTensor<T, N>* out) {
in->share(0)->lshift(rhs, out->mutable_share(0));
in->share(1)->lshift(rhs, out->mutable_share(1));
};
// abs = val - 2 * sign * val
auto abs = [lshift] (const FixedPointTensor<T, N>* in,
const BooleanTensor<T>* sign,
FixedPointTensor<T, N>* out) {
lshift(in, 1, out);
sign->mul(out, out);
in->sub(out, out);
};
auto out0 = tensor_factory()->template create<T>(ret->shape());
abs(this, &sign_lhs, &abs_lhs);
abs(rhs, &sign_rhs, &abs_rhs);
for (ssize_t i = int_len - 1; i >= 0; --i) {
lshift(&abs_rhs, i, &sub_rhs);
abs_lhs.gt(&sub_rhs, &cmp_res);
cmp_res.mul(&sub_rhs, &sub_rhs);
cmp_res.lshift(N + i, &cmp_res);
abs_lhs.sub(&sub_rhs, &abs_lhs);
cmp_res.bitwise_xor(&cmp_res_all, &cmp_res_all);
}
for (size_t i = 1; i <= N; ++i) {