forked from secretflow/spu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfxp_base.cc
395 lines (310 loc) · 12.2 KB
/
fxp_base.cc
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
// Copyright 2021 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/fxp_base.h"
#include <cmath>
#include "libspu/core/prelude.h"
#include "libspu/core/trace.h"
#include "libspu/kernel/hal/constants.h"
#include "libspu/kernel/hal/fxp_cleartext.h"
#include "libspu/kernel/hal/ring.h"
namespace spu::kernel::hal {
namespace detail {
// Calc:
// y = c0 + x*c1 + x^2*c2 + x^3*c3 + ... + x^n*c[n]
Value polynomial(SPUContext* ctx, const Value& x,
absl::Span<Value const> coeffs, SignType sign_x,
SignType sign_ret) {
SPU_TRACE_HAL_DISP(ctx, x);
SPU_ENFORCE(x.isFxp());
SPU_ENFORCE(!coeffs.empty());
if (coeffs.size() == 1U) {
return coeffs[0];
}
Value x_pow = constant(ctx, 1.0F, x.dtype(), x.shape());
Value res = _mul(ctx, x_pow, coeffs[0]);
const auto fbits = ctx->getFxpBits();
for (size_t i = 1; i < coeffs.size(); i++) {
if ((i & 1) == 0U) {
// x^{even order} is always positive
x_pow = _trunc(ctx, _mul(ctx, x_pow, x), fbits, SignType::Positive);
} else {
if (i > 1) {
x_pow = _trunc(ctx, _mul(ctx, x_pow, x), fbits, sign_x);
} else {
// i=1, then save a _trunc
x_pow = x;
}
}
res = _add(ctx, res, _mul(ctx, x_pow, coeffs[i]));
}
return _trunc(ctx, res, fbits, sign_ret).setDtype(x.dtype());
}
Value polynomial(SPUContext* ctx, const Value& x,
absl::Span<float const> coeffs, SignType sign_x,
SignType sign_ret) {
std::vector<Value> cs;
cs.reserve(coeffs.size());
for (const auto& c : coeffs) {
cs.push_back(constant(ctx, c, x.dtype(), x.shape()));
}
return polynomial(ctx, x, cs, sign_x, sign_ret);
}
Value highestOneBit(SPUContext* ctx, const Value& x) {
auto y = _prefix_or(ctx, x);
auto y1 = _rshift(ctx, y, {1});
return _xor(ctx, y, y1);
}
// FIXME:
// Use range propagation instead of directly set.
// or expose bit_decompose as mpc level api.
void hintNumberOfBits(const Value& a, size_t nbits) {
if (a.storage_type().isa<BShare>()) {
const_cast<Type&>(a.storage_type()).as<BShare>()->setNbits(nbits);
}
}
Value maskNumberOfBits(SPUContext* ctx, const Value& in, size_t nbits) {
auto k1 = constant(ctx, static_cast<int64_t>(1), spu::DT_I64, in.shape());
auto mask = _sub(ctx, _lshift(ctx, k1, {static_cast<int64_t>(nbits)}), k1);
auto out = _and(ctx, in, mask).setDtype(in.dtype());
return out;
}
namespace {
Value reciprocal_goldschmidt_normalized_approx(SPUContext* ctx,
const Value& b_abs,
const Value& factor) {
// compute normalize x_abs, [0.5, 1)
auto c = f_mul(ctx, b_abs, factor, SignType::Positive);
// initial guess:
// w = 1/c ≈ 2.9142 - 2c when c >= 0.5 and c < 1
const auto k2 = _constant(ctx, 2, c.shape());
const auto k2_9142 = constant(ctx, 2.9142F, b_abs.dtype(), c.shape());
auto w = f_sub(ctx, k2_9142, _mul(ctx, k2, c).setDtype(b_abs.dtype()));
// init r=w, e=1-c*w
const auto& k1_ = constant(ctx, 1.0F, b_abs.dtype(), c.shape());
auto r = w;
auto e = f_sub(ctx, k1_, f_mul(ctx, c, w, SignType::Positive));
size_t num_iters = ctx->config().fxp_div_goldschmidt_iters();
if (ctx->getFxpBits() >= 30) {
// default 2 iters of goldschmidt can only get precision about 14 bits.
// so if fxp>=30, we use 3 iters by default, which get about 28 bits
// precision.
num_iters = std::max(num_iters, static_cast<size_t>(3));
}
SPU_ENFORCE(num_iters != 0, "fxp_div_goldschmidt_iters should not be {}",
num_iters);
// iterate, r=r(1+e), e=e*e
for (size_t itr = 0; itr < num_iters; itr++) {
r = f_mul(ctx, r, f_add(ctx, e, k1_), SignType::Positive);
if (itr + 1 < num_iters) {
e = f_square(ctx, e);
}
}
return r;
}
} // namespace
// Reference:
// Chapter 3.4 Division @ Secure Computation With Fixed Point Number
// http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.221.1305&rep=rep1&type=pdf
//
// Goldschmidt main idea:
// Target:
// calculate a/b
//
// Symbols:
// f: number of fractional bits in fixed point.
// m: the highest position of bit with value == 1.
//
// Initial guess:
// let b = c*2^{m} where c = normalize(x), c \in [0.5, 1)
// let w = 1/c ≈ (2.9142 - 2*c) as the initial guess.
//
// Iteration (reduce error):
// let r = w, denotes result
// let e = 1-c*w, denotes error
// for _ in iters:
// r = r(1 + e)
// e = e * e
//
// return r * a * 2^{-m}
//
// Precision is decided by magic number, i.e 2.9142 and f.
Value div_goldschmidt_general(SPUContext* ctx, const Value& a, const Value& b,
SignType a_sign, SignType b_sign) {
Value b_abs;
Value is_negative;
if (b_sign == SignType::Unknown) {
// We prefer b_abs = b < 0 ? -b : b over b_abs = sign(b) * b
// because MulA1B is a better choice than MulAA for CHEETAH.
// For ABY3, these two computations give the same cost though.
is_negative = _msb(ctx, b);
// insert ``prefer_a'' because the msb bit are used twice.
is_negative = _prefer_a(ctx, is_negative);
b_abs = _mux(ctx, is_negative, _negate(ctx, b), b).setDtype(b.dtype());
} else if (b_sign == SignType::Positive) {
is_negative = _constant(ctx, 0, b.shape());
b_abs = b;
} else {
// b is negative
is_negative = _constant(ctx, static_cast<uint128_t>(1), b.shape());
b_abs = _negate(ctx, b).setDtype(b.dtype());
}
auto b_msb = detail::highestOneBit(ctx, b_abs);
// factor = 2^{f-m} = 2^{-m} * 2^f, the fixed point repr of 2^{-m}
const size_t num_fxp_bits = ctx->getFxpBits();
auto factor = _bitrev(ctx, b_msb, 0, 2 * num_fxp_bits).setDtype(b.dtype());
factor = maskNumberOfBits(ctx, factor, 2 * num_fxp_bits);
// also, we use factor twice
factor = _prefer_a(ctx, factor);
// compute approximation of normalize b_abs
auto r = reciprocal_goldschmidt_normalized_approx(ctx, b_abs, factor);
// r from goldschmidt iteration is always positive
// so sign(r*a) = sign(a)
r = f_mul(ctx, r, a, a_sign);
// also, sign(r*factor) = sign(r)
r = f_mul(ctx, r, factor, a_sign);
return _mux(ctx, is_negative, _negate(ctx, r), r).setDtype(a.dtype());
}
Value div_goldschmidt(SPUContext* ctx, const Value& a, const Value& b) {
SPU_TRACE_HAL_DISP(ctx, a, b);
return div_goldschmidt_general(ctx, a, b);
}
Value reciprocal_goldschmidt_positive(SPUContext* ctx, const Value& b_abs) {
SPU_TRACE_HAL_DISP(ctx, b_abs);
auto b_msb = detail::highestOneBit(ctx, b_abs);
// factor = 2^{f-m} = 2^{-m} * 2^f, the fixed point repr of 2^{-m}
const size_t num_fxp_bits = ctx->getFxpBits();
auto factor =
_bitrev(ctx, b_msb, 0, 2 * num_fxp_bits).setDtype(b_abs.dtype());
factor = maskNumberOfBits(ctx, factor, 2 * num_fxp_bits);
// also, we use factor twice
factor = _prefer_a(ctx, factor);
// compute approximation of normalize b_abs
auto r = reciprocal_goldschmidt_normalized_approx(ctx, b_abs, factor);
return f_mul(ctx, r, factor, SignType::Positive);
}
// NOTE(junfeng): we have a separate reciprocal_goldschmidt is to avoid
// unnecessary f_mul for y initiation in div_goldschmidt.
Value reciprocal_goldschmidt(SPUContext* ctx, const Value& b) {
SPU_TRACE_HAL_DISP(ctx, b);
// We prefer b_abs = b < 0 ? -b : b over b_abs = sign(b) * b
// because MulA1B is a better choice than MulAA for CHEETAH.
// For ABY3, these two computations give the same cost though.
auto is_negative = _msb(ctx, b);
// insert ``prefer_a'' because the msb bit are used twice.
is_negative = _prefer_a(ctx, is_negative);
auto b_abs = _mux(ctx, is_negative, _negate(ctx, b), b).setDtype(b.dtype());
auto b_msb = detail::highestOneBit(ctx, b_abs);
// factor = 2^{f-m} = 2^{-m} * 2^f, the fixed point repr of 2^{-m}
const size_t num_fxp_bits = ctx->getFxpBits();
auto factor = _bitrev(ctx, b_msb, 0, 2 * num_fxp_bits).setDtype(b.dtype());
factor = maskNumberOfBits(ctx, factor, 2 * num_fxp_bits);
// also, we use factor twice
factor = _prefer_a(ctx, factor);
// compute approximation of normalize b_abs
auto r = reciprocal_goldschmidt_normalized_approx(ctx, b_abs, factor);
r = f_mul(ctx, r, factor, SignType::Positive);
return _mux(ctx, is_negative, _negate(ctx, r), r).setDtype(b.dtype());
}
} // namespace detail
Value f_negate(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp());
return _negate(ctx, x).setDtype(x.dtype());
}
Value f_abs(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp());
const Value sign = _sign(ctx, x);
return _mul(ctx, sign, x).setDtype(x.dtype());
}
Value f_reciprocal(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp());
if (x.isPublic()) {
return f_reciprocal_p(ctx, x);
}
return detail::reciprocal_goldschmidt(ctx, x);
}
Value f_add(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _add(ctx, x, y).setDtype(x.dtype());
}
Value f_sub(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return f_add(ctx, x, f_negate(ctx, y));
}
Value f_mul(SPUContext* ctx, const Value& x, const Value& y, SignType sign) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _trunc(ctx, _mul(ctx, x, y), ctx->getFxpBits(), sign)
.setDtype(x.dtype());
}
Value f_mmul(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _trunc(ctx, _mmul(ctx, x, y)).setDtype(x.dtype());
}
Value f_conv2d(SPUContext* ctx, const Value& x, const Value& y,
const Strides& window_strides) {
SPU_TRACE_HAL_LEAF(ctx, x, y, window_strides);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _trunc(ctx, _conv2d(ctx, x, y, window_strides)).setDtype(x.dtype());
}
Value f_tensordot(SPUContext* ctx, const Value& x, const Value& y,
const Index& ix, const Index& iy) {
SPU_TRACE_HAL_LEAF(ctx, x, y, ix, iy);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _trunc(ctx, _tensordot(ctx, x, y, ix, iy)).setDtype(x.dtype());
}
Value f_div(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
if (x.isPublic() && y.isPublic()) {
return f_div_p(ctx, x, y);
}
return detail::div_goldschmidt(ctx, x, y);
}
Value f_equal(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _equal(ctx, x, y).setDtype(DT_I1);
}
Value f_less(SPUContext* ctx, const Value& x, const Value& y) {
SPU_TRACE_HAL_LEAF(ctx, x, y);
SPU_ENFORCE(x.isFxp() && y.isFxp() && x.dtype() == y.dtype());
return _less(ctx, x, y).setDtype(DT_I1);
}
Value f_square(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp(), "{}", x);
return _trunc(ctx, _square(ctx, x), ctx->getFxpBits(), SignType::Positive)
.setDtype(x.dtype());
}
Value f_floor(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp());
const int64_t fbits = ctx->getFxpBits();
return _lshift(ctx, _arshift(ctx, x, {fbits}), {fbits}).setDtype(x.dtype());
}
Value f_ceil(SPUContext* ctx, const Value& x) {
SPU_TRACE_HAL_LEAF(ctx, x);
SPU_ENFORCE(x.isFxp());
// ceil(x) = floor(x + 1.0 - epsilon)
const auto k1 = constant(ctx, 1.0F, x.dtype(), x.shape());
return f_floor(
ctx, f_add(ctx, x, f_sub(ctx, k1, epsilon(ctx, x.dtype(), x.shape()))));
}
} // namespace spu::kernel::hal