Debian Codegraph @

include/plink2_fmath.h

raw
1 #ifndef __PLINK2_FMATH_H__
2 #define __PLINK2_FMATH_H__
3
4 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This library is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation, either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 // Most of the functions are C ports of Shigeo Mitsunari's fast math library
21 // functions posted at https://github.com/herumi/fmath . The original license
22 // is https://opensource.org/licenses/BSD-3-Clause .
23 // I've added comments to expd() which reflect my understanding of the
24 // algorithm; these are BSD-licensed.
25
26 #include "plink2_base.h"
27
28 #include <math.h>
29
30 #ifdef __cplusplus
31 namespace plink2 {
32 #endif
33
34 #ifdef __LP64__
35 # ifdef FVEC_32
36 extern const uint32_t kFloatExpLookupInt[] __attribute__((aligned(32)));
37 # else
38 extern const uint32_t kFloatExpLookupInt[] __attribute__((aligned(16)));
39 # endif
40
41 # ifdef FVEC_32
42 HEADER_INLINE VecF fmath_exp_ps(VecF xxv) {
43 __m256 xx = FToVec(xxv);
44 const __m256i mask7ff = _mm256_set1_epi32(0x7fffffff);
45 // 88
46 const __m256i max_x = _mm256_set1_epi32(0x42b00000);
47 // -88
48 // more sensible 0xc2b00000... not used here due to "narrowing conversion"
49 // warning
50 const __m256i min_x = _mm256_set1_epi64x(-0x3d4fffff3d500000LL);
51 // 2^10 / log(2)
52 const __m256i const_aa = _mm256_set1_epi32(0x44b8aa3b);
53 // log(2) / 2^10
54 const __m256i const_bb = _mm256_set1_epi32(0x3a317218);
55 const __m256i f1 = _mm256_set1_epi32(0x3f800000);
56 const __m256i mask_s = _mm256_set1_epi32(0x000003ff);
57 const __m256i i127s = _mm256_set1_epi32(0x0001fc00);
58 const __m256i limit = _mm256_castps_si256(_mm256_and_ps(xx, R_CAST(__m256, mask7ff)));
59 const int32_t over = _mm256_movemask_epi8(_mm256_cmpgt_epi32(limit, max_x));
60 if (over) {
61 xx = _mm256_min_ps(xx, R_CAST(__m256, max_x));
62 xx = _mm256_max_ps(xx, R_CAST(__m256, min_x));
63 }
64 const __m256i rr = _mm256_cvtps_epi32(_mm256_mul_ps(xx, R_CAST(__m256, const_aa)));
65 __m256 tt = _mm256_fnmadd_ps(_mm256_cvtepi32_ps(rr), R_CAST(__m256, const_bb), xx);
66 tt = _mm256_add_ps(R_CAST(__m256, f1), tt);
67 const __m256i v8 = _mm256_and_si256(rr, mask_s);
68 __m256i u8 = _mm256_add_epi32(rr, i127s);
69 u8 = _mm256_srli_epi32(u8, 10);
70 u8 = _mm256_slli_epi32(u8, 23);
71 __m256i ti = _mm256_i32gather_epi32(R_CAST(const int*, kFloatExpLookupInt), v8, 4);
72 __m256 t0 = _mm256_castsi256_ps(ti);
73 t0 = _mm256_or_ps(t0, _mm256_castsi256_ps(u8));
74 return R_CAST(VecF, _mm256_mul_ps(tt, t0));
75 }
76 # else // !FVEC_32
77 static inline VecF fmath_exp_ps(VecF xxv) {
78 const float* const kFloatExpLookup = R_CAST(const float*, kFloatExpLookupInt);
79 __m128 xx = xxv;
80 const __m128i mask7ff = _mm_set1_epi32(0x7fffffff);
81
82 // 88
83 const __m128i max_x = _mm_set1_epi32(0x42b00000);
84 // -88
85 // more sensible 0xc2b00000... not used here due to "narrowing conversion"
86 // warning
87 const __m128i min_x = _mm_set1_epi64x(-0x3d4fffff3d500000LL);
88 // 2^10 / log(2)
89 const __m128i const_aa = _mm_set1_epi32(0x44b8aa3b);
90 // log(2) / 2^10
91 const __m128i const_bb = _mm_set1_epi32(0x3a317218);
92
93 const __m128i f1 = _mm_set1_epi32(0x3f800000);
94 const __m128i mask_s = _mm_set1_epi64x(0x3ff000003ffLLU);
95 const __m128i i127s = _mm_set1_epi32(0x0001fc00);
96 const __m128i limit = _mm_castps_si128(_mm_and_ps(xx, R_CAST(__m128, mask7ff)));
97 const int32_t over = _mm_movemask_epi8(_mm_cmpgt_epi32(limit, max_x));
98 if (over) {
99 xx = _mm_min_ps(xx, R_CAST(__m128, max_x));
100 xx = _mm_max_ps(xx, R_CAST(__m128, min_x));
101 }
102 const __m128i rr = _mm_cvtps_epi32(_mm_mul_ps(xx, R_CAST(__m128, const_aa)));
103 __m128 tt = _mm_sub_ps(xx, _mm_mul_ps(_mm_cvtepi32_ps(rr), R_CAST(__m128, const_bb)));
104 tt = _mm_add_ps(tt, R_CAST(__m128, f1));
105 const __m128i v4 = _mm_and_si128(rr, mask_s);
106 __m128i u4 = _mm_add_epi32(rr, i127s);
107 u4 = _mm_srli_epi32(u4, 10);
108 u4 = _mm_slli_epi32(u4, 23);
109 const uint32_t v0 = _mm_cvtsi128_si32(v4);
110 // uint32_t v1 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(2)));
111 // uint32_t v2 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(4)));
112 // uint32_t v3 = ((int32_t)(uint16_t)__builtin_ia32_vec_ext_v8hi((__v8hi)(__m128i)(v4), (int32_t)(6)));
113 // make this work with LLVM
114 const uint32_t v1 = _mm_extract_epi16(R_CAST(__m128i, v4), 2);
115 const uint32_t v2 = _mm_extract_epi16(R_CAST(__m128i, v4), 4);
116 const uint32_t v3 = _mm_extract_epi16(R_CAST(__m128i, v4), 6);
117
118 __m128 t0 = _mm_set_ss(kFloatExpLookup[v0]);
119 __m128 t1 = _mm_set_ss(kFloatExpLookup[v1]);
120 const __m128 t2 = _mm_set_ss(kFloatExpLookup[v2]);
121 const __m128 t3 = _mm_set_ss(kFloatExpLookup[v3]);
122 t1 = _mm_movelh_ps(t1, t3);
123 t1 = _mm_castsi128_ps(_mm_slli_epi64(_mm_castps_si128(t1), 32));
124 t0 = _mm_movelh_ps(t0, t2);
125 t0 = _mm_or_ps(t0, t1);
126 t0 = _mm_or_ps(t0, _mm_castsi128_ps(u4));
127 tt = _mm_mul_ps(tt, t0);
128 return R_CAST(VecF, tt);
129 }
130 # endif
131
132 CONSTI32(kFmathExpdSbit, 11);
133 CONSTI32(kFmathExpdS, 1 << kFmathExpdSbit);
134 CONSTI32(kFmathExpdAdj, kFmathExpdS * 0x3ff);
135 static const double kFmathExpdC1 = 1.0;
136 // I assume Mitsunari adjusted these constants slightly (away from 1/6 and 3)
137 // to reduce empirical error.
138 static const double kFmathExpdC2 = 0.16666666685227835064;
139 static const double kFmathExpdC3 = 3.0000000027955394;
140 static const double kFmathExpdA = S_CAST(double, kFmathExpdS) / kLn2;
141 static const double kFmathExpdRa = kLn2 / S_CAST(double, kFmathExpdS);
142
143 # ifdef FVEC_32
144 extern const uint64_t kExpdLookupInt[] __attribute__((aligned(32)));
145 # else
146 extern const uint64_t kExpdLookupInt[] __attribute__((aligned(16)));
147 # endif
148
149 typedef union {
150 double d8;
151 uint64_t u8;
152 } __uni8;
153
154 // Assumes x is within the expd() bounds.
155 HEADER_INLINE double expd_bounded(double x) {
156 const uint64_t b = 3ULL << 51;
157 // kFmathExpdA is 1 / log(2^{1/2048}), so y := x * kFmathExpdA satisfies
158 // e^x == (2^{1/2048})^y
159 // Then, we set d := 1.5 * 2^52 + y. Recall that IEEE-754 doubles have 52
160 // mantissa bits, with an implicit leading '1'. |y| is far smaller than
161 // 2^51, so we know 2^52 < d < 2^53; thus, the exponent bits correspond to a
162 // multiplier of 1. The low mantissa bits of d correspond to y rounded to
163 // the nearest (signed) integer; call this value yi.
164 __uni8 di;
165 di.d8 = x * kFmathExpdA + b;
166 // Define z := yi * log(2^{1/2048}).
167 // kExpdLookupInt is a 2048-entry table encoding the mantissa bits of
168 // 2^{0/2048}, 2^{1/2048}, ..., 2^{2047/2048}. From this value, we can
169 // easily determine e^z.
170 const uint64_t iax = kExpdLookupInt[di.u8 & (kFmathExpdS - 1)];
171
172 // Calculate (z - x). Under the default rounding mode, the absolute value
173 // should not be larger than log(2^{1/2048}) / 2.
174 const double t = (di.d8 - b) * kFmathExpdRa - x;
175 const uint64_t u = ((di.u8 + kFmathExpdAdj) >> kFmathExpdSbit) << 52;
176 // We're now ready to use the Taylor expansion of e^x about x=z.
177 // e^x = f(z) - f'(z)(z-x) + f''(z)((z-x)^2)/2 - f'''(z)((z-x)^3)/6 + ...
178 // Conveniently, f(z) = f'(z) = f''(z) = f'''(z), so we can factor it out and
179 // just multiply by it at the end.
180 // We can stop the Taylor expansion after the cubic term since |((z-x)^4)/24|
181 // is guaranteed to be smaller than 4e-17, and the (1 - (z-x) + ((z-x)^2)/2 -
182 // ((z-x)^3)/6) expression it's being added to is guaranteed to be larger
183 // than 0.5, so the quartic term would never affect even the least
184 // significant bit.
185 const double y = (kFmathExpdC3 - t) * (t * t) * kFmathExpdC2 - t + kFmathExpdC1;
186
187 di.u8 = u | iax;
188 return y * di.d8;
189 }
190
191 // Maximum error of this function is ~6 ulps; there's some rounding error in
192 // the multiply operations, etc.
193 HEADER_INLINE double expd(double x) {
194 if (x <= -708.39641853226414) {
195 // Changed from the original bound of -708.39641853226408, since that
196 // produced inconsistent results between expd() and expd_v() in my testing.
197 // The proper value of this constant depends on the floating-point rounding
198 // mode.
199 return 0;
200 }
201 if (x >= 709.78254366799815) {
202 // This bound is also changed (from 709.78271289338397), though in this
203 // case the change doesn't affect behavior.
204 return S_CAST(double, INFINITY);
205 }
206 return expd_bounded(x);
207 }
208
209 // Requires vector-alignment.
210 HEADER_INLINE void expd_v(double* px, uintptr_t n) {
211 const double b = S_CAST(double, 3ULL << 51);
212 # ifdef FVEC_32
213 const uintptr_t r = n & 3;
214 n &= ~3;
215 const __m256d mC1 = _mm256_set1_pd(kFmathExpdC1);
216 const __m256d mC2 = _mm256_set1_pd(kFmathExpdC2);
217 const __m256d mC3 = _mm256_set1_pd(kFmathExpdC3);
218 const __m256d ma = _mm256_set1_pd(kFmathExpdA);
219 const __m256d mra = _mm256_set1_pd(kFmathExpdRa);
220 const __m256i madj = _mm256_set1_epi64x(kFmathExpdAdj);
221 const __m256i maskSbit = _mm256_set1_epi64x(kFmathExpdS - 1);
222 const __m256d expMax = _mm256_set1_pd(709.78254366799815);
223 const __m256d expMin = _mm256_set1_pd(-708.39641853226414);
224 for (size_t i = 0; i < n; i += 4) {
225 __m256d x = _mm256_load_pd(px);
226 x = _mm256_min_pd(x, expMax);
227 x = _mm256_max_pd(x, expMin);
228
229 __m256d d = _mm256_mul_pd(x, ma);
230 d = _mm256_add_pd(d, _mm256_set1_pd(b));
231 const __m256i adr = _mm256_and_si256(_mm256_castpd_si256(d), maskSbit);
232 const __m256i iax = _mm256_i64gather_epi64(R_CAST(const long long*, kExpdLookupInt), adr, 8);
233 const __m256d t = _mm256_sub_pd(_mm256_mul_pd(_mm256_sub_pd(d, _mm256_set1_pd(b)), mra), x);
234 __m256i u = _mm256_castpd_si256(d);
235 u = _mm256_add_epi64(u, madj);
236 u = _mm256_srli_epi64(u, kFmathExpdSbit);
237 u = _mm256_slli_epi64(u, 52);
238 u = _mm256_or_si256(u, iax);
239 __m256d y = _mm256_mul_pd(_mm256_sub_pd(mC3, t), _mm256_mul_pd(t, t));
240 y = _mm256_mul_pd(y, mC2);
241 y = _mm256_add_pd(_mm256_sub_pd(y, t), mC1);
242 _mm256_store_pd(px, _mm256_mul_pd(y, _mm256_castsi256_pd(u)));
243 px += 4;
244 }
245 # else
246 const uintptr_t r = n & 1;
247 n &= ~1;
248 const __m128d mC1 = _mm_set1_pd(kFmathExpdC1);
249 const __m128d mC2 = _mm_set1_pd(kFmathExpdC2);
250 const __m128d mC3 = _mm_set1_pd(kFmathExpdC3);
251 const __m128d ma = _mm_set1_pd(kFmathExpdA);
252 const __m128d mra = _mm_set1_pd(kFmathExpdRa);
253 # if defined(__x86_64__) || defined(_WIN64)
254 const __m128i madj = _mm_set1_epi64x(kFmathExpdAdj);
255 # else
256 const __m128i madj = _mm_set_epi32(0, kFmathExpdAdj, 0, kFmathExpdAdj);
257 # endif
258 const __m128d expMax = _mm_set1_pd(709.78254366799815);
259 const __m128d expMin = _mm_set1_pd(-708.39641853226414);
260 for (size_t i = 0; i < n; i += 2) {
261 __m128d x = _mm_load_pd(px);
262 x = _mm_min_pd(x, expMax);
263 x = _mm_max_pd(x, expMin);
264
265 __m128d d = _mm_mul_pd(x, ma);
266 d = _mm_add_pd(d, _mm_set1_pd(b));
267 const int adr0 = _mm_cvtsi128_si32(_mm_castpd_si128(d)) & (kFmathExpdS - 1);
268 const int adr1 = _mm_cvtsi128_si32(_mm_srli_si128(_mm_castpd_si128(d), 8)) & (kFmathExpdS - 1);
269
270 const __m128i iaxL = _mm_castpd_si128(_mm_load_sd(R_CAST(const double*, &(kExpdLookupInt[adr0]))));
271 __m128i iax = _mm_castpd_si128(_mm_load_sd(R_CAST(const double*, &(kExpdLookupInt[adr1]))));
272 iax = _mm_unpacklo_epi64(iaxL, iax);
273
274 const __m128d t = _mm_sub_pd(_mm_mul_pd(_mm_sub_pd(d, _mm_set1_pd(b)), mra), x);
275 __m128i u = _mm_castpd_si128(d);
276 u = _mm_add_epi64(u, madj);
277 u = _mm_srli_epi64(u, kFmathExpdSbit);
278 u = _mm_slli_epi64(u, 52);
279 u = _mm_or_si128(u, iax);
280 __m128d y = _mm_mul_pd(_mm_sub_pd(mC3, t), _mm_mul_pd(t, t));
281 y = _mm_mul_pd(y, mC2);
282 y = _mm_add_pd(_mm_sub_pd(y, t), mC1);
283 _mm_store_pd(px, _mm_mul_pd(y, _mm_castsi128_pd(u)));
284 px += 2;
285 }
286 # endif
287 for (uintptr_t i = 0; i < r; ++i) {
288 px[i] = expd(px[i]);
289 }
290 }
291
292 // 1 / (1 + e^{-x}).
293 // Looked into approximating this function directly instead of going through
294 // expd_bounded(), but I couldn't find a better approach.
295 HEADER_INLINE double logistic(double x) {
296 if (x <= -708.39641853226414) {
297 // Even though expd_bounded(-x) returns a finite value down to -709.78...,
298 // the reciprocal of that value is only representable as a denormal double,
299 // and plink2 disables denormals.
300 return 0.0;
301 }
302 // As soon as e^{-x} is smaller than ~2^{-53}, the result rounds up to 1.
303 if (x >= 36.736800569677098) {
304 return 1.0;
305 }
306 return 1.0 / (1.0 + expd_bounded(-x));
307 }
308
309 // In-place vector 1 / (1 + e^{-x}).
310 // Requires vector-alignment, and clobbers trailing entries.
311 HEADER_INLINE void logistic_v_unsafe(double* px, uintptr_t n) {
312 const double b = S_CAST(double, 3ULL << 51);
313 # ifdef FVEC_32
314 const __m256d mC1 = _mm256_set1_pd(kFmathExpdC1);
315 const __m256d mC2 = _mm256_set1_pd(kFmathExpdC2);
316 const __m256d mC3 = _mm256_set1_pd(kFmathExpdC3);
317 const __m256d mnega = _mm256_set1_pd(-kFmathExpdA);
318 const __m256d mra = _mm256_set1_pd(kFmathExpdRa);
319 const __m256i madj = _mm256_set1_epi64x(kFmathExpdAdj);
320 const __m256i maskSbit = _mm256_set1_epi64x(kFmathExpdS - 1);
321 const __m256d expMax = _mm256_set1_pd(36.736800569677098);
322 const __m256d expMin = _mm256_set1_pd(-708.39641853226414);
323 for (size_t i = 0; i < n; i += 4) {
324 __m256d x = _mm256_load_pd(px);
325 x = _mm256_min_pd(x, expMax);
326 x = _mm256_max_pd(x, expMin);
327
328 // We want e^{-x}, not e^x.
329 __m256d d = _mm256_mul_pd(x, mnega);
330 d = _mm256_add_pd(d, _mm256_set1_pd(b));
331 const __m256i adr = _mm256_and_si256(_mm256_castpd_si256(d), maskSbit);
332 const __m256i iax = _mm256_i64gather_epi64(R_CAST(const long long*, kExpdLookupInt), adr, 8);
333 // Subtract -x -> add x.
334 const __m256d t = _mm256_add_pd(_mm256_mul_pd(_mm256_sub_pd(d, _mm256_set1_pd(b)), mra), x);
335 __m256i u = _mm256_castpd_si256(d);
336 u = _mm256_add_epi64(u, madj);
337 u = _mm256_srli_epi64(u, kFmathExpdSbit);
338 u = _mm256_slli_epi64(u, 52);
339 u = _mm256_or_si256(u, iax);
340 __m256d y = _mm256_mul_pd(_mm256_sub_pd(mC3, t), _mm256_mul_pd(t, t));
341 y = _mm256_mul_pd(y, mC2);
342 y = _mm256_add_pd(_mm256_sub_pd(y, t), mC1);
343 const __m256d enegx = _mm256_mul_pd(y, _mm256_castsi256_pd(u));
344 // Add 1, then take the reciprocal, to get the final result.
345 _mm256_store_pd(px, _mm256_div_pd(mC1, _mm256_add_pd(mC1, enegx)));
346 px += 4;
347 }
348 # else
349 const __m128d mC1 = _mm_set1_pd(kFmathExpdC1);
350 const __m128d mC2 = _mm_set1_pd(kFmathExpdC2);
351 const __m128d mC3 = _mm_set1_pd(kFmathExpdC3);
352 const __m128d mnega = _mm_set1_pd(-kFmathExpdA);
353 const __m128d mra = _mm_set1_pd(kFmathExpdRa);
354 # if defined(__x86_64__) || defined(_WIN64)
355 const __m128i madj = _mm_set1_epi64x(kFmathExpdAdj);
356 # else
357 const __m128i madj = _mm_set_epi32(0, kFmathExpdAdj, 0, kFmathExpdAdj);
358 # endif
359 const __m128d expMax = _mm_set1_pd(36.736800569677098);
360 const __m128d expMin = _mm_set1_pd(-708.39641853226414);
361 for (size_t i = 0; i < n; i += 2) {
362 __m128d x = _mm_load_pd(px);
363 x = _mm_min_pd(x, expMax);
364 x = _mm_max_pd(x, expMin);
365
366 __m128d d = _mm_mul_pd(x, mnega);
367 d = _mm_add_pd(d, _mm_set1_pd(b));
368 const int adr0 = _mm_cvtsi128_si32(_mm_castpd_si128(d)) & (kFmathExpdS - 1);
369 const int adr1 = _mm_cvtsi128_si32(_mm_srli_si128(_mm_castpd_si128(d), 8)) & (kFmathExpdS - 1);
370
371 const __m128i iaxL = _mm_castpd_si128(_mm_load_sd(R_CAST(const double*, &(kExpdLookupInt[adr0]))));
372 __m128i iax = _mm_castpd_si128(_mm_load_sd(R_CAST(const double*, &(kExpdLookupInt[adr1]))));
373 iax = _mm_unpacklo_epi64(iaxL, iax);
374
375 const __m128d t = _mm_add_pd(_mm_mul_pd(_mm_sub_pd(d, _mm_set1_pd(b)), mra), x);
376 __m128i u = _mm_castpd_si128(d);
377 u = _mm_add_epi64(u, madj);
378 u = _mm_srli_epi64(u, kFmathExpdSbit);
379 u = _mm_slli_epi64(u, 52);
380 u = _mm_or_si128(u, iax);
381 __m128d y = _mm_mul_pd(_mm_sub_pd(mC3, t), _mm_mul_pd(t, t));
382 y = _mm_mul_pd(y, mC2);
383 y = _mm_add_pd(_mm_sub_pd(y, t), mC1);
384 const __m128d enegx = _mm_mul_pd(y, _mm_castsi128_pd(u));
385 _mm_store_pd(px, _mm_div_pd(mC1, _mm_add_pd(mC1, enegx)));
386 px += 2;
387 }
388 # endif
389 }
390
391 HEADER_INLINE void logistic_v(double* px, uintptr_t n) {
392 const uintptr_t r = n % kDoublePerDVec;
393 n = RoundDownPow2(n, kDoublePerDVec);
394 logistic_v_unsafe(px, n);
395 px = &(px[n]);
396 for (uintptr_t i = 0; i < r; ++i) {
397 px[i] = logistic(px[i]);
398 }
399 }
400
401 #else // !__LP64__
402 HEADER_INLINE double expd(double x) {
403 return exp(x);
404 }
405
406 HEADER_INLINE void expd_v(double* px, uintptr_t n) {
407 for (uintptr_t ulii = 0; ulii != n; ++ulii) {
408 px[ulii] = exp(px[ulii]);
409 }
410 }
411
412 HEADER_INLINE double logistic(double x) {
413 return 1.0 / (1.0 + exp(-x));
414 }
415
416 HEADER_INLINE void logistic_v_unsafe(double* px, uintptr_t n) {
417 for (uintptr_t ulii = 0; ulii != n; ++ulii) {
418 px[ulii] = logistic(px[ulii]);
419 }
420 }
421
422 HEADER_INLINE void logistic_v(double* px, uintptr_t n) {
423 logistic_v_unsafe(px, n);
424 }
425 #endif
426
427
428
429 #ifdef __cplusplus
430 }
431 #endif
432
433 #endif // __PLINK2_FMATH_H__