1*da0073e9SAndroid Build Coastguard Worker #pragma once
2*da0073e9SAndroid Build Coastguard Worker
3*da0073e9SAndroid Build Coastguard Worker /// Defines the Half type (half-precision floating-point) including conversions
4*da0073e9SAndroid Build Coastguard Worker /// to standard C types and basic arithmetic operations. Note that arithmetic
5*da0073e9SAndroid Build Coastguard Worker /// operations are implemented by converting to floating point and
6*da0073e9SAndroid Build Coastguard Worker /// performing the operation in float32, instead of using CUDA half intrinsics.
7*da0073e9SAndroid Build Coastguard Worker /// Most uses of this type within ATen are memory bound, including the
8*da0073e9SAndroid Build Coastguard Worker /// element-wise kernels, and the half intrinsics aren't efficient on all GPUs.
9*da0073e9SAndroid Build Coastguard Worker /// If you are writing a compute bound kernel, you can use the CUDA half
10*da0073e9SAndroid Build Coastguard Worker /// intrinsics directly on the Half type from device code.
11*da0073e9SAndroid Build Coastguard Worker
12*da0073e9SAndroid Build Coastguard Worker #include <c10/macros/Export.h>
13*da0073e9SAndroid Build Coastguard Worker #include <c10/macros/Macros.h>
14*da0073e9SAndroid Build Coastguard Worker #include <c10/util/TypeSafeSignMath.h>
15*da0073e9SAndroid Build Coastguard Worker #include <c10/util/bit_cast.h>
16*da0073e9SAndroid Build Coastguard Worker #include <c10/util/complex.h>
17*da0073e9SAndroid Build Coastguard Worker #include <c10/util/floating_point_utils.h>
18*da0073e9SAndroid Build Coastguard Worker #include <type_traits>
19*da0073e9SAndroid Build Coastguard Worker
20*da0073e9SAndroid Build Coastguard Worker #if defined(__cplusplus)
21*da0073e9SAndroid Build Coastguard Worker #include <cmath>
22*da0073e9SAndroid Build Coastguard Worker #elif !defined(__OPENCL_VERSION__)
23*da0073e9SAndroid Build Coastguard Worker #include <math.h>
24*da0073e9SAndroid Build Coastguard Worker #endif
25*da0073e9SAndroid Build Coastguard Worker
26*da0073e9SAndroid Build Coastguard Worker #ifdef _MSC_VER
27*da0073e9SAndroid Build Coastguard Worker #include <intrin.h>
28*da0073e9SAndroid Build Coastguard Worker #endif
29*da0073e9SAndroid Build Coastguard Worker
30*da0073e9SAndroid Build Coastguard Worker #include <cstdint>
31*da0073e9SAndroid Build Coastguard Worker #include <cstring>
32*da0073e9SAndroid Build Coastguard Worker #include <iosfwd>
33*da0073e9SAndroid Build Coastguard Worker #include <limits>
34*da0073e9SAndroid Build Coastguard Worker #include <ostream>
35*da0073e9SAndroid Build Coastguard Worker
36*da0073e9SAndroid Build Coastguard Worker #ifdef __CUDACC__
37*da0073e9SAndroid Build Coastguard Worker #include <cuda_fp16.h>
38*da0073e9SAndroid Build Coastguard Worker #endif
39*da0073e9SAndroid Build Coastguard Worker
40*da0073e9SAndroid Build Coastguard Worker #ifdef __HIPCC__
41*da0073e9SAndroid Build Coastguard Worker #include <hip/hip_fp16.h>
42*da0073e9SAndroid Build Coastguard Worker #endif
43*da0073e9SAndroid Build Coastguard Worker
44*da0073e9SAndroid Build Coastguard Worker #if defined(CL_SYCL_LANGUAGE_VERSION)
45*da0073e9SAndroid Build Coastguard Worker #include <CL/sycl.hpp> // for SYCL 1.2.1
46*da0073e9SAndroid Build Coastguard Worker #elif defined(SYCL_LANGUAGE_VERSION)
47*da0073e9SAndroid Build Coastguard Worker #include <sycl/sycl.hpp> // for SYCL 2020
48*da0073e9SAndroid Build Coastguard Worker #endif
49*da0073e9SAndroid Build Coastguard Worker
50*da0073e9SAndroid Build Coastguard Worker #if defined(__aarch64__) && !defined(__CUDACC__)
51*da0073e9SAndroid Build Coastguard Worker #include <arm_neon.h>
52*da0073e9SAndroid Build Coastguard Worker #endif
53*da0073e9SAndroid Build Coastguard Worker
54*da0073e9SAndroid Build Coastguard Worker namespace c10 {
55*da0073e9SAndroid Build Coastguard Worker
56*da0073e9SAndroid Build Coastguard Worker namespace detail {
57*da0073e9SAndroid Build Coastguard Worker
58*da0073e9SAndroid Build Coastguard Worker /*
59*da0073e9SAndroid Build Coastguard Worker * Convert a 16-bit floating-point number in IEEE half-precision format, in bit
60*da0073e9SAndroid Build Coastguard Worker * representation, to a 32-bit floating-point number in IEEE single-precision
61*da0073e9SAndroid Build Coastguard Worker * format, in bit representation.
62*da0073e9SAndroid Build Coastguard Worker *
63*da0073e9SAndroid Build Coastguard Worker * @note The implementation doesn't use any floating-point operations.
64*da0073e9SAndroid Build Coastguard Worker */
fp16_ieee_to_fp32_bits(uint16_t h)65*da0073e9SAndroid Build Coastguard Worker inline uint32_t fp16_ieee_to_fp32_bits(uint16_t h) {
66*da0073e9SAndroid Build Coastguard Worker /*
67*da0073e9SAndroid Build Coastguard Worker * Extend the half-precision floating-point number to 32 bits and shift to the
68*da0073e9SAndroid Build Coastguard Worker * upper part of the 32-bit word:
69*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
70*da0073e9SAndroid Build Coastguard Worker * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
71*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
72*da0073e9SAndroid Build Coastguard Worker * Bits 31 26-30 16-25 0-15
73*da0073e9SAndroid Build Coastguard Worker *
74*da0073e9SAndroid Build Coastguard Worker * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
75*da0073e9SAndroid Build Coastguard Worker * - zero bits.
76*da0073e9SAndroid Build Coastguard Worker */
77*da0073e9SAndroid Build Coastguard Worker const uint32_t w = (uint32_t)h << 16;
78*da0073e9SAndroid Build Coastguard Worker /*
79*da0073e9SAndroid Build Coastguard Worker * Extract the sign of the input number into the high bit of the 32-bit word:
80*da0073e9SAndroid Build Coastguard Worker *
81*da0073e9SAndroid Build Coastguard Worker * +---+----------------------------------+
82*da0073e9SAndroid Build Coastguard Worker * | S |0000000 00000000 00000000 00000000|
83*da0073e9SAndroid Build Coastguard Worker * +---+----------------------------------+
84*da0073e9SAndroid Build Coastguard Worker * Bits 31 0-31
85*da0073e9SAndroid Build Coastguard Worker */
86*da0073e9SAndroid Build Coastguard Worker const uint32_t sign = w & UINT32_C(0x80000000);
87*da0073e9SAndroid Build Coastguard Worker /*
88*da0073e9SAndroid Build Coastguard Worker * Extract mantissa and biased exponent of the input number into the bits 0-30
89*da0073e9SAndroid Build Coastguard Worker * of the 32-bit word:
90*da0073e9SAndroid Build Coastguard Worker *
91*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
92*da0073e9SAndroid Build Coastguard Worker * | 0 |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
93*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
94*da0073e9SAndroid Build Coastguard Worker * Bits 30 27-31 17-26 0-16
95*da0073e9SAndroid Build Coastguard Worker */
96*da0073e9SAndroid Build Coastguard Worker const uint32_t nonsign = w & UINT32_C(0x7FFFFFFF);
97*da0073e9SAndroid Build Coastguard Worker /*
98*da0073e9SAndroid Build Coastguard Worker * Renorm shift is the number of bits to shift mantissa left to make the
99*da0073e9SAndroid Build Coastguard Worker * half-precision number normalized. If the initial number is normalized, some
100*da0073e9SAndroid Build Coastguard Worker * of its high 6 bits (sign == 0 and 5-bit exponent) equals one. In this case
101*da0073e9SAndroid Build Coastguard Worker * renorm_shift == 0. If the number is denormalize, renorm_shift > 0. Note
102*da0073e9SAndroid Build Coastguard Worker * that if we shift denormalized nonsign by renorm_shift, the unit bit of
103*da0073e9SAndroid Build Coastguard Worker * mantissa will shift into exponent, turning the biased exponent into 1, and
104*da0073e9SAndroid Build Coastguard Worker * making mantissa normalized (i.e. without leading 1).
105*da0073e9SAndroid Build Coastguard Worker */
106*da0073e9SAndroid Build Coastguard Worker #ifdef _MSC_VER
107*da0073e9SAndroid Build Coastguard Worker unsigned long nonsign_bsr;
108*da0073e9SAndroid Build Coastguard Worker _BitScanReverse(&nonsign_bsr, (unsigned long)nonsign);
109*da0073e9SAndroid Build Coastguard Worker uint32_t renorm_shift = (uint32_t)nonsign_bsr ^ 31;
110*da0073e9SAndroid Build Coastguard Worker #else
111*da0073e9SAndroid Build Coastguard Worker uint32_t renorm_shift = __builtin_clz(nonsign);
112*da0073e9SAndroid Build Coastguard Worker #endif
113*da0073e9SAndroid Build Coastguard Worker renorm_shift = renorm_shift > 5 ? renorm_shift - 5 : 0;
114*da0073e9SAndroid Build Coastguard Worker /*
115*da0073e9SAndroid Build Coastguard Worker * Iff half-precision number has exponent of 15, the addition overflows
116*da0073e9SAndroid Build Coastguard Worker * it into bit 31, and the subsequent shift turns the high 9 bits
117*da0073e9SAndroid Build Coastguard Worker * into 1. Thus inf_nan_mask == 0x7F800000 if the half-precision number
118*da0073e9SAndroid Build Coastguard Worker * had exponent of 15 (i.e. was NaN or infinity) 0x00000000 otherwise
119*da0073e9SAndroid Build Coastguard Worker */
120*da0073e9SAndroid Build Coastguard Worker const int32_t inf_nan_mask =
121*da0073e9SAndroid Build Coastguard Worker ((int32_t)(nonsign + 0x04000000) >> 8) & INT32_C(0x7F800000);
122*da0073e9SAndroid Build Coastguard Worker /*
123*da0073e9SAndroid Build Coastguard Worker * Iff nonsign is 0, it overflows into 0xFFFFFFFF, turning bit 31
124*da0073e9SAndroid Build Coastguard Worker * into 1. Otherwise, bit 31 remains 0. The signed shift right by 31
125*da0073e9SAndroid Build Coastguard Worker * broadcasts bit 31 into all bits of the zero_mask. Thus zero_mask ==
126*da0073e9SAndroid Build Coastguard Worker * 0xFFFFFFFF if the half-precision number was zero (+0.0h or -0.0h)
127*da0073e9SAndroid Build Coastguard Worker * 0x00000000 otherwise
128*da0073e9SAndroid Build Coastguard Worker */
129*da0073e9SAndroid Build Coastguard Worker const int32_t zero_mask = (int32_t)(nonsign - 1) >> 31;
130*da0073e9SAndroid Build Coastguard Worker /*
131*da0073e9SAndroid Build Coastguard Worker * 1. Shift nonsign left by renorm_shift to normalize it (if the input
132*da0073e9SAndroid Build Coastguard Worker * was denormal)
133*da0073e9SAndroid Build Coastguard Worker * 2. Shift nonsign right by 3 so the exponent (5 bits originally)
134*da0073e9SAndroid Build Coastguard Worker * becomes an 8-bit field and 10-bit mantissa shifts into the 10 high
135*da0073e9SAndroid Build Coastguard Worker * bits of the 23-bit mantissa of IEEE single-precision number.
136*da0073e9SAndroid Build Coastguard Worker * 3. Add 0x70 to the exponent (starting at bit 23) to compensate the
137*da0073e9SAndroid Build Coastguard Worker * different in exponent bias (0x7F for single-precision number less 0xF
138*da0073e9SAndroid Build Coastguard Worker * for half-precision number).
139*da0073e9SAndroid Build Coastguard Worker * 4. Subtract renorm_shift from the exponent (starting at bit 23) to
140*da0073e9SAndroid Build Coastguard Worker * account for renormalization. As renorm_shift is less than 0x70, this
141*da0073e9SAndroid Build Coastguard Worker * can be combined with step 3.
142*da0073e9SAndroid Build Coastguard Worker * 5. Binary OR with inf_nan_mask to turn the exponent into 0xFF if the
143*da0073e9SAndroid Build Coastguard Worker * input was NaN or infinity.
144*da0073e9SAndroid Build Coastguard Worker * 6. Binary ANDNOT with zero_mask to turn the mantissa and exponent
145*da0073e9SAndroid Build Coastguard Worker * into zero if the input was zero.
146*da0073e9SAndroid Build Coastguard Worker * 7. Combine with the sign of the input number.
147*da0073e9SAndroid Build Coastguard Worker */
148*da0073e9SAndroid Build Coastguard Worker return sign |
149*da0073e9SAndroid Build Coastguard Worker ((((nonsign << renorm_shift >> 3) + ((0x70 - renorm_shift) << 23)) |
150*da0073e9SAndroid Build Coastguard Worker inf_nan_mask) &
151*da0073e9SAndroid Build Coastguard Worker ~zero_mask);
152*da0073e9SAndroid Build Coastguard Worker }
153*da0073e9SAndroid Build Coastguard Worker
154*da0073e9SAndroid Build Coastguard Worker /*
155*da0073e9SAndroid Build Coastguard Worker * Convert a 16-bit floating-point number in IEEE half-precision format, in bit
156*da0073e9SAndroid Build Coastguard Worker * representation, to a 32-bit floating-point number in IEEE single-precision
157*da0073e9SAndroid Build Coastguard Worker * format.
158*da0073e9SAndroid Build Coastguard Worker *
159*da0073e9SAndroid Build Coastguard Worker * @note The implementation relies on IEEE-like (no assumption about rounding
160*da0073e9SAndroid Build Coastguard Worker * mode and no operations on denormals) floating-point operations and bitcasts
161*da0073e9SAndroid Build Coastguard Worker * between integer and floating-point variables.
162*da0073e9SAndroid Build Coastguard Worker */
fp16_ieee_to_fp32_value(uint16_t h)163*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE inline float fp16_ieee_to_fp32_value(uint16_t h) {
164*da0073e9SAndroid Build Coastguard Worker /*
165*da0073e9SAndroid Build Coastguard Worker * Extend the half-precision floating-point number to 32 bits and shift to the
166*da0073e9SAndroid Build Coastguard Worker * upper part of the 32-bit word:
167*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
168*da0073e9SAndroid Build Coastguard Worker * | S |EEEEE|MM MMMM MMMM|0000 0000 0000 0000|
169*da0073e9SAndroid Build Coastguard Worker * +---+-----+------------+-------------------+
170*da0073e9SAndroid Build Coastguard Worker * Bits 31 26-30 16-25 0-15
171*da0073e9SAndroid Build Coastguard Worker *
172*da0073e9SAndroid Build Coastguard Worker * S - sign bit, E - bits of the biased exponent, M - bits of the mantissa, 0
173*da0073e9SAndroid Build Coastguard Worker * - zero bits.
174*da0073e9SAndroid Build Coastguard Worker */
175*da0073e9SAndroid Build Coastguard Worker const uint32_t w = (uint32_t)h << 16;
176*da0073e9SAndroid Build Coastguard Worker /*
177*da0073e9SAndroid Build Coastguard Worker * Extract the sign of the input number into the high bit of the 32-bit word:
178*da0073e9SAndroid Build Coastguard Worker *
179*da0073e9SAndroid Build Coastguard Worker * +---+----------------------------------+
180*da0073e9SAndroid Build Coastguard Worker * | S |0000000 00000000 00000000 00000000|
181*da0073e9SAndroid Build Coastguard Worker * +---+----------------------------------+
182*da0073e9SAndroid Build Coastguard Worker * Bits 31 0-31
183*da0073e9SAndroid Build Coastguard Worker */
184*da0073e9SAndroid Build Coastguard Worker const uint32_t sign = w & UINT32_C(0x80000000);
185*da0073e9SAndroid Build Coastguard Worker /*
186*da0073e9SAndroid Build Coastguard Worker * Extract mantissa and biased exponent of the input number into the high bits
187*da0073e9SAndroid Build Coastguard Worker * of the 32-bit word:
188*da0073e9SAndroid Build Coastguard Worker *
189*da0073e9SAndroid Build Coastguard Worker * +-----+------------+---------------------+
190*da0073e9SAndroid Build Coastguard Worker * |EEEEE|MM MMMM MMMM|0 0000 0000 0000 0000|
191*da0073e9SAndroid Build Coastguard Worker * +-----+------------+---------------------+
192*da0073e9SAndroid Build Coastguard Worker * Bits 27-31 17-26 0-16
193*da0073e9SAndroid Build Coastguard Worker */
194*da0073e9SAndroid Build Coastguard Worker const uint32_t two_w = w + w;
195*da0073e9SAndroid Build Coastguard Worker
196*da0073e9SAndroid Build Coastguard Worker /*
197*da0073e9SAndroid Build Coastguard Worker * Shift mantissa and exponent into bits 23-28 and bits 13-22 so they become
198*da0073e9SAndroid Build Coastguard Worker * mantissa and exponent of a single-precision floating-point number:
199*da0073e9SAndroid Build Coastguard Worker *
200*da0073e9SAndroid Build Coastguard Worker * S|Exponent | Mantissa
201*da0073e9SAndroid Build Coastguard Worker * +-+---+-----+------------+----------------+
202*da0073e9SAndroid Build Coastguard Worker * |0|000|EEEEE|MM MMMM MMMM|0 0000 0000 0000|
203*da0073e9SAndroid Build Coastguard Worker * +-+---+-----+------------+----------------+
204*da0073e9SAndroid Build Coastguard Worker * Bits | 23-31 | 0-22
205*da0073e9SAndroid Build Coastguard Worker *
206*da0073e9SAndroid Build Coastguard Worker * Next, there are some adjustments to the exponent:
207*da0073e9SAndroid Build Coastguard Worker * - The exponent needs to be corrected by the difference in exponent bias
208*da0073e9SAndroid Build Coastguard Worker * between single-precision and half-precision formats (0x7F - 0xF = 0x70)
209*da0073e9SAndroid Build Coastguard Worker * - Inf and NaN values in the inputs should become Inf and NaN values after
210*da0073e9SAndroid Build Coastguard Worker * conversion to the single-precision number. Therefore, if the biased
211*da0073e9SAndroid Build Coastguard Worker * exponent of the half-precision input was 0x1F (max possible value), the
212*da0073e9SAndroid Build Coastguard Worker * biased exponent of the single-precision output must be 0xFF (max possible
213*da0073e9SAndroid Build Coastguard Worker * value). We do this correction in two steps:
214*da0073e9SAndroid Build Coastguard Worker * - First, we adjust the exponent by (0xFF - 0x1F) = 0xE0 (see exp_offset
215*da0073e9SAndroid Build Coastguard Worker * below) rather than by 0x70 suggested by the difference in the exponent bias
216*da0073e9SAndroid Build Coastguard Worker * (see above).
217*da0073e9SAndroid Build Coastguard Worker * - Then we multiply the single-precision result of exponent adjustment by
218*da0073e9SAndroid Build Coastguard Worker * 2**(-112) to reverse the effect of exponent adjustment by 0xE0 less the
219*da0073e9SAndroid Build Coastguard Worker * necessary exponent adjustment by 0x70 due to difference in exponent bias.
220*da0073e9SAndroid Build Coastguard Worker * The floating-point multiplication hardware would ensure than Inf and
221*da0073e9SAndroid Build Coastguard Worker * NaN would retain their value on at least partially IEEE754-compliant
222*da0073e9SAndroid Build Coastguard Worker * implementations.
223*da0073e9SAndroid Build Coastguard Worker *
224*da0073e9SAndroid Build Coastguard Worker * Note that the above operations do not handle denormal inputs (where biased
225*da0073e9SAndroid Build Coastguard Worker * exponent == 0). However, they also do not operate on denormal inputs, and
226*da0073e9SAndroid Build Coastguard Worker * do not produce denormal results.
227*da0073e9SAndroid Build Coastguard Worker */
228*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t exp_offset = UINT32_C(0xE0) << 23;
229*da0073e9SAndroid Build Coastguard Worker // const float exp_scale = 0x1.0p-112f;
230*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t scale_bits = (uint32_t)15 << 23;
231*da0073e9SAndroid Build Coastguard Worker float exp_scale_val = 0;
232*da0073e9SAndroid Build Coastguard Worker std::memcpy(&exp_scale_val, &scale_bits, sizeof(exp_scale_val));
233*da0073e9SAndroid Build Coastguard Worker const float exp_scale = exp_scale_val;
234*da0073e9SAndroid Build Coastguard Worker const float normalized_value =
235*da0073e9SAndroid Build Coastguard Worker fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
236*da0073e9SAndroid Build Coastguard Worker
237*da0073e9SAndroid Build Coastguard Worker /*
238*da0073e9SAndroid Build Coastguard Worker * Convert denormalized half-precision inputs into single-precision results
239*da0073e9SAndroid Build Coastguard Worker * (always normalized). Zero inputs are also handled here.
240*da0073e9SAndroid Build Coastguard Worker *
241*da0073e9SAndroid Build Coastguard Worker * In a denormalized number the biased exponent is zero, and mantissa has
242*da0073e9SAndroid Build Coastguard Worker * on-zero bits. First, we shift mantissa into bits 0-9 of the 32-bit word.
243*da0073e9SAndroid Build Coastguard Worker *
244*da0073e9SAndroid Build Coastguard Worker * zeros | mantissa
245*da0073e9SAndroid Build Coastguard Worker * +---------------------------+------------+
246*da0073e9SAndroid Build Coastguard Worker * |0000 0000 0000 0000 0000 00|MM MMMM MMMM|
247*da0073e9SAndroid Build Coastguard Worker * +---------------------------+------------+
248*da0073e9SAndroid Build Coastguard Worker * Bits 10-31 0-9
249*da0073e9SAndroid Build Coastguard Worker *
250*da0073e9SAndroid Build Coastguard Worker * Now, remember that denormalized half-precision numbers are represented as:
251*da0073e9SAndroid Build Coastguard Worker * FP16 = mantissa * 2**(-24).
252*da0073e9SAndroid Build Coastguard Worker * The trick is to construct a normalized single-precision number with the
253*da0073e9SAndroid Build Coastguard Worker * same mantissa and thehalf-precision input and with an exponent which would
254*da0073e9SAndroid Build Coastguard Worker * scale the corresponding mantissa bits to 2**(-24). A normalized
255*da0073e9SAndroid Build Coastguard Worker * single-precision floating-point number is represented as: FP32 = (1 +
256*da0073e9SAndroid Build Coastguard Worker * mantissa * 2**(-23)) * 2**(exponent - 127) Therefore, when the biased
257*da0073e9SAndroid Build Coastguard Worker * exponent is 126, a unit change in the mantissa of the input denormalized
258*da0073e9SAndroid Build Coastguard Worker * half-precision number causes a change of the constructed single-precision
259*da0073e9SAndroid Build Coastguard Worker * number by 2**(-24), i.e. the same amount.
260*da0073e9SAndroid Build Coastguard Worker *
261*da0073e9SAndroid Build Coastguard Worker * The last step is to adjust the bias of the constructed single-precision
262*da0073e9SAndroid Build Coastguard Worker * number. When the input half-precision number is zero, the constructed
263*da0073e9SAndroid Build Coastguard Worker * single-precision number has the value of FP32 = 1 * 2**(126 - 127) =
264*da0073e9SAndroid Build Coastguard Worker * 2**(-1) = 0.5 Therefore, we need to subtract 0.5 from the constructed
265*da0073e9SAndroid Build Coastguard Worker * single-precision number to get the numerical equivalent of the input
266*da0073e9SAndroid Build Coastguard Worker * half-precision number.
267*da0073e9SAndroid Build Coastguard Worker */
268*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t magic_mask = UINT32_C(126) << 23;
269*da0073e9SAndroid Build Coastguard Worker constexpr float magic_bias = 0.5f;
270*da0073e9SAndroid Build Coastguard Worker const float denormalized_value =
271*da0073e9SAndroid Build Coastguard Worker fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
272*da0073e9SAndroid Build Coastguard Worker
273*da0073e9SAndroid Build Coastguard Worker /*
274*da0073e9SAndroid Build Coastguard Worker * - Choose either results of conversion of input as a normalized number, or
275*da0073e9SAndroid Build Coastguard Worker * as a denormalized number, depending on the input exponent. The variable
276*da0073e9SAndroid Build Coastguard Worker * two_w contains input exponent in bits 27-31, therefore if its smaller than
277*da0073e9SAndroid Build Coastguard Worker * 2**27, the input is either a denormal number, or zero.
278*da0073e9SAndroid Build Coastguard Worker * - Combine the result of conversion of exponent and mantissa with the sign
279*da0073e9SAndroid Build Coastguard Worker * of the input number.
280*da0073e9SAndroid Build Coastguard Worker */
281*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t denormalized_cutoff = UINT32_C(1) << 27;
282*da0073e9SAndroid Build Coastguard Worker const uint32_t result = sign |
283*da0073e9SAndroid Build Coastguard Worker (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value)
284*da0073e9SAndroid Build Coastguard Worker : fp32_to_bits(normalized_value));
285*da0073e9SAndroid Build Coastguard Worker return fp32_from_bits(result);
286*da0073e9SAndroid Build Coastguard Worker }
287*da0073e9SAndroid Build Coastguard Worker
288*da0073e9SAndroid Build Coastguard Worker /*
289*da0073e9SAndroid Build Coastguard Worker * Convert a 32-bit floating-point number in IEEE single-precision format to a
290*da0073e9SAndroid Build Coastguard Worker * 16-bit floating-point number in IEEE half-precision format, in bit
291*da0073e9SAndroid Build Coastguard Worker * representation.
292*da0073e9SAndroid Build Coastguard Worker *
293*da0073e9SAndroid Build Coastguard Worker * @note The implementation relies on IEEE-like (no assumption about rounding
294*da0073e9SAndroid Build Coastguard Worker * mode and no operations on denormals) floating-point operations and bitcasts
295*da0073e9SAndroid Build Coastguard Worker * between integer and floating-point variables.
296*da0073e9SAndroid Build Coastguard Worker */
fp16_ieee_from_fp32_value(float f)297*da0073e9SAndroid Build Coastguard Worker inline uint16_t fp16_ieee_from_fp32_value(float f) {
298*da0073e9SAndroid Build Coastguard Worker // const float scale_to_inf = 0x1.0p+112f;
299*da0073e9SAndroid Build Coastguard Worker // const float scale_to_zero = 0x1.0p-110f;
300*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t scale_to_inf_bits = (uint32_t)239 << 23;
301*da0073e9SAndroid Build Coastguard Worker constexpr uint32_t scale_to_zero_bits = (uint32_t)17 << 23;
302*da0073e9SAndroid Build Coastguard Worker float scale_to_inf_val = 0, scale_to_zero_val = 0;
303*da0073e9SAndroid Build Coastguard Worker std::memcpy(&scale_to_inf_val, &scale_to_inf_bits, sizeof(scale_to_inf_val));
304*da0073e9SAndroid Build Coastguard Worker std::memcpy(
305*da0073e9SAndroid Build Coastguard Worker &scale_to_zero_val, &scale_to_zero_bits, sizeof(scale_to_zero_val));
306*da0073e9SAndroid Build Coastguard Worker const float scale_to_inf = scale_to_inf_val;
307*da0073e9SAndroid Build Coastguard Worker const float scale_to_zero = scale_to_zero_val;
308*da0073e9SAndroid Build Coastguard Worker
309*da0073e9SAndroid Build Coastguard Worker #if defined(_MSC_VER) && _MSC_VER == 1916
310*da0073e9SAndroid Build Coastguard Worker float base = ((signbit(f) != 0 ? -f : f) * scale_to_inf) * scale_to_zero;
311*da0073e9SAndroid Build Coastguard Worker #else
312*da0073e9SAndroid Build Coastguard Worker float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
313*da0073e9SAndroid Build Coastguard Worker #endif
314*da0073e9SAndroid Build Coastguard Worker
315*da0073e9SAndroid Build Coastguard Worker const uint32_t w = fp32_to_bits(f);
316*da0073e9SAndroid Build Coastguard Worker const uint32_t shl1_w = w + w;
317*da0073e9SAndroid Build Coastguard Worker const uint32_t sign = w & UINT32_C(0x80000000);
318*da0073e9SAndroid Build Coastguard Worker uint32_t bias = shl1_w & UINT32_C(0xFF000000);
319*da0073e9SAndroid Build Coastguard Worker if (bias < UINT32_C(0x71000000)) {
320*da0073e9SAndroid Build Coastguard Worker bias = UINT32_C(0x71000000);
321*da0073e9SAndroid Build Coastguard Worker }
322*da0073e9SAndroid Build Coastguard Worker
323*da0073e9SAndroid Build Coastguard Worker base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
324*da0073e9SAndroid Build Coastguard Worker const uint32_t bits = fp32_to_bits(base);
325*da0073e9SAndroid Build Coastguard Worker const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
326*da0073e9SAndroid Build Coastguard Worker const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
327*da0073e9SAndroid Build Coastguard Worker const uint32_t nonsign = exp_bits + mantissa_bits;
328*da0073e9SAndroid Build Coastguard Worker return static_cast<uint16_t>(
329*da0073e9SAndroid Build Coastguard Worker (sign >> 16) |
330*da0073e9SAndroid Build Coastguard Worker (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign));
331*da0073e9SAndroid Build Coastguard Worker }
332*da0073e9SAndroid Build Coastguard Worker
333*da0073e9SAndroid Build Coastguard Worker #if defined(__aarch64__) && !defined(__CUDACC__)
fp16_from_bits(uint16_t h)334*da0073e9SAndroid Build Coastguard Worker inline float16_t fp16_from_bits(uint16_t h) {
335*da0073e9SAndroid Build Coastguard Worker return c10::bit_cast<float16_t>(h);
336*da0073e9SAndroid Build Coastguard Worker }
337*da0073e9SAndroid Build Coastguard Worker
fp16_to_bits(float16_t f)338*da0073e9SAndroid Build Coastguard Worker inline uint16_t fp16_to_bits(float16_t f) {
339*da0073e9SAndroid Build Coastguard Worker return c10::bit_cast<uint16_t>(f);
340*da0073e9SAndroid Build Coastguard Worker }
341*da0073e9SAndroid Build Coastguard Worker
342*da0073e9SAndroid Build Coastguard Worker // According to https://godbolt.org/z/frExdbsWG it would translate to single
343*da0073e9SAndroid Build Coastguard Worker // fcvt s0, h0
native_fp16_to_fp32_value(uint16_t h)344*da0073e9SAndroid Build Coastguard Worker inline float native_fp16_to_fp32_value(uint16_t h) {
345*da0073e9SAndroid Build Coastguard Worker return static_cast<float>(fp16_from_bits(h));
346*da0073e9SAndroid Build Coastguard Worker }
347*da0073e9SAndroid Build Coastguard Worker
native_fp16_from_fp32_value(float f)348*da0073e9SAndroid Build Coastguard Worker inline uint16_t native_fp16_from_fp32_value(float f) {
349*da0073e9SAndroid Build Coastguard Worker return fp16_to_bits(static_cast<float16_t>(f));
350*da0073e9SAndroid Build Coastguard Worker }
351*da0073e9SAndroid Build Coastguard Worker #endif
352*da0073e9SAndroid Build Coastguard Worker
353*da0073e9SAndroid Build Coastguard Worker } // namespace detail
354*da0073e9SAndroid Build Coastguard Worker
355*da0073e9SAndroid Build Coastguard Worker struct alignas(2) Half {
356*da0073e9SAndroid Build Coastguard Worker unsigned short x;
357*da0073e9SAndroid Build Coastguard Worker
358*da0073e9SAndroid Build Coastguard Worker struct from_bits_t {};
from_bitsHalf359*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE static constexpr from_bits_t from_bits() {
360*da0073e9SAndroid Build Coastguard Worker return from_bits_t();
361*da0073e9SAndroid Build Coastguard Worker }
362*da0073e9SAndroid Build Coastguard Worker
363*da0073e9SAndroid Build Coastguard Worker // HIP wants __host__ __device__ tag, CUDA does not
364*da0073e9SAndroid Build Coastguard Worker #if defined(USE_ROCM)
365*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE Half() = default;
366*da0073e9SAndroid Build Coastguard Worker #else
367*da0073e9SAndroid Build Coastguard Worker Half() = default;
368*da0073e9SAndroid Build Coastguard Worker #endif
369*da0073e9SAndroid Build Coastguard Worker
HalfHalf370*da0073e9SAndroid Build Coastguard Worker constexpr C10_HOST_DEVICE Half(unsigned short bits, from_bits_t) : x(bits) {}
371*da0073e9SAndroid Build Coastguard Worker #if defined(__aarch64__) && !defined(__CUDACC__)
372*da0073e9SAndroid Build Coastguard Worker inline Half(float16_t value);
373*da0073e9SAndroid Build Coastguard Worker inline operator float16_t() const;
374*da0073e9SAndroid Build Coastguard Worker #else
375*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE Half(float value);
376*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE operator float() const;
377*da0073e9SAndroid Build Coastguard Worker #endif
378*da0073e9SAndroid Build Coastguard Worker
379*da0073e9SAndroid Build Coastguard Worker #if defined(__CUDACC__) || defined(__HIPCC__)
380*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE Half(const __half& value);
381*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE operator __half() const;
382*da0073e9SAndroid Build Coastguard Worker #endif
383*da0073e9SAndroid Build Coastguard Worker #ifdef SYCL_LANGUAGE_VERSION
384*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE Half(const sycl::half& value);
385*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE operator sycl::half() const;
386*da0073e9SAndroid Build Coastguard Worker #endif
387*da0073e9SAndroid Build Coastguard Worker };
388*da0073e9SAndroid Build Coastguard Worker
389*da0073e9SAndroid Build Coastguard Worker // TODO : move to complex.h
390*da0073e9SAndroid Build Coastguard Worker template <>
391*da0073e9SAndroid Build Coastguard Worker struct alignas(4) complex<Half> {
392*da0073e9SAndroid Build Coastguard Worker Half real_;
393*da0073e9SAndroid Build Coastguard Worker Half imag_;
394*da0073e9SAndroid Build Coastguard Worker
395*da0073e9SAndroid Build Coastguard Worker // Constructors
396*da0073e9SAndroid Build Coastguard Worker complex() = default;
397*da0073e9SAndroid Build Coastguard Worker // Half constructor is not constexpr so the following constructor can't
398*da0073e9SAndroid Build Coastguard Worker // be constexpr
399*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE explicit inline complex(const Half& real, const Half& imag)
400*da0073e9SAndroid Build Coastguard Worker : real_(real), imag_(imag) {}
401*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE inline complex(const c10::complex<float>& value)
402*da0073e9SAndroid Build Coastguard Worker : real_(value.real()), imag_(value.imag()) {}
403*da0073e9SAndroid Build Coastguard Worker
404*da0073e9SAndroid Build Coastguard Worker // Conversion operator
405*da0073e9SAndroid Build Coastguard Worker inline C10_HOST_DEVICE operator c10::complex<float>() const {
406*da0073e9SAndroid Build Coastguard Worker return {real_, imag_};
407*da0073e9SAndroid Build Coastguard Worker }
408*da0073e9SAndroid Build Coastguard Worker
409*da0073e9SAndroid Build Coastguard Worker constexpr C10_HOST_DEVICE Half real() const {
410*da0073e9SAndroid Build Coastguard Worker return real_;
411*da0073e9SAndroid Build Coastguard Worker }
412*da0073e9SAndroid Build Coastguard Worker constexpr C10_HOST_DEVICE Half imag() const {
413*da0073e9SAndroid Build Coastguard Worker return imag_;
414*da0073e9SAndroid Build Coastguard Worker }
415*da0073e9SAndroid Build Coastguard Worker
416*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE complex<Half>& operator+=(const complex<Half>& other) {
417*da0073e9SAndroid Build Coastguard Worker real_ = static_cast<float>(real_) + static_cast<float>(other.real_);
418*da0073e9SAndroid Build Coastguard Worker imag_ = static_cast<float>(imag_) + static_cast<float>(other.imag_);
419*da0073e9SAndroid Build Coastguard Worker return *this;
420*da0073e9SAndroid Build Coastguard Worker }
421*da0073e9SAndroid Build Coastguard Worker
422*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE complex<Half>& operator-=(const complex<Half>& other) {
423*da0073e9SAndroid Build Coastguard Worker real_ = static_cast<float>(real_) - static_cast<float>(other.real_);
424*da0073e9SAndroid Build Coastguard Worker imag_ = static_cast<float>(imag_) - static_cast<float>(other.imag_);
425*da0073e9SAndroid Build Coastguard Worker return *this;
426*da0073e9SAndroid Build Coastguard Worker }
427*da0073e9SAndroid Build Coastguard Worker
428*da0073e9SAndroid Build Coastguard Worker C10_HOST_DEVICE complex<Half>& operator*=(const complex<Half>& other) {
429*da0073e9SAndroid Build Coastguard Worker auto a = static_cast<float>(real_);
430*da0073e9SAndroid Build Coastguard Worker auto b = static_cast<float>(imag_);
431*da0073e9SAndroid Build Coastguard Worker auto c = static_cast<float>(other.real());
432*da0073e9SAndroid Build Coastguard Worker auto d = static_cast<float>(other.imag());
433*da0073e9SAndroid Build Coastguard Worker real_ = a * c - b * d;
434*da0073e9SAndroid Build Coastguard Worker imag_ = a * d + b * c;
435*da0073e9SAndroid Build Coastguard Worker return *this;
436*da0073e9SAndroid Build Coastguard Worker }
437*da0073e9SAndroid Build Coastguard Worker };
438*da0073e9SAndroid Build Coastguard Worker
439*da0073e9SAndroid Build Coastguard Worker // In some versions of MSVC, there will be a compiler error when building.
440*da0073e9SAndroid Build Coastguard Worker // C4146: unary minus operator applied to unsigned type, result still unsigned
441*da0073e9SAndroid Build Coastguard Worker // C4804: unsafe use of type 'bool' in operation
442*da0073e9SAndroid Build Coastguard Worker // It can be addressed by disabling the following warning.
443*da0073e9SAndroid Build Coastguard Worker #ifdef _MSC_VER
444*da0073e9SAndroid Build Coastguard Worker #pragma warning(push)
445*da0073e9SAndroid Build Coastguard Worker #pragma warning(disable : 4146)
446*da0073e9SAndroid Build Coastguard Worker #pragma warning(disable : 4804)
447*da0073e9SAndroid Build Coastguard Worker #pragma warning(disable : 4018)
448*da0073e9SAndroid Build Coastguard Worker #endif
449*da0073e9SAndroid Build Coastguard Worker
450*da0073e9SAndroid Build Coastguard Worker // The overflow checks may involve float to int conversion which may
451*da0073e9SAndroid Build Coastguard Worker // trigger precision loss warning. Re-enable the warning once the code
452*da0073e9SAndroid Build Coastguard Worker // is fixed. See T58053069.
453*da0073e9SAndroid Build Coastguard Worker C10_CLANG_DIAGNOSTIC_PUSH()
454*da0073e9SAndroid Build Coastguard Worker #if C10_CLANG_HAS_WARNING("-Wimplicit-float-conversion")
455*da0073e9SAndroid Build Coastguard Worker C10_CLANG_DIAGNOSTIC_IGNORE("-Wimplicit-float-conversion")
456*da0073e9SAndroid Build Coastguard Worker #endif
457*da0073e9SAndroid Build Coastguard Worker
458*da0073e9SAndroid Build Coastguard Worker // bool can be converted to any type.
459*da0073e9SAndroid Build Coastguard Worker // Without specializing on bool, in pytorch_linux_trusty_py2_7_9_build:
460*da0073e9SAndroid Build Coastguard Worker // `error: comparison of constant '255' with boolean expression is always false`
461*da0073e9SAndroid Build Coastguard Worker // for `f > limit::max()` below
462*da0073e9SAndroid Build Coastguard Worker template <typename To, typename From>
463*da0073e9SAndroid Build Coastguard Worker std::enable_if_t<std::is_same_v<From, bool>, bool> overflows(
464*da0073e9SAndroid Build Coastguard Worker From /*f*/,
465*da0073e9SAndroid Build Coastguard Worker bool strict_unsigned [[maybe_unused]] = false) {
466*da0073e9SAndroid Build Coastguard Worker return false;
467*da0073e9SAndroid Build Coastguard Worker }
468*da0073e9SAndroid Build Coastguard Worker
469*da0073e9SAndroid Build Coastguard Worker // skip isnan and isinf check for integral types
470*da0073e9SAndroid Build Coastguard Worker template <typename To, typename From>
471*da0073e9SAndroid Build Coastguard Worker std::enable_if_t<std::is_integral_v<From> && !std::is_same_v<From, bool>, bool>
472*da0073e9SAndroid Build Coastguard Worker overflows(From f, bool strict_unsigned = false) {
473*da0073e9SAndroid Build Coastguard Worker using limit = std::numeric_limits<typename scalar_value_type<To>::type>;
474*da0073e9SAndroid Build Coastguard Worker if constexpr (!limit::is_signed && std::numeric_limits<From>::is_signed) {
475*da0073e9SAndroid Build Coastguard Worker // allow for negative numbers to wrap using two's complement arithmetic.
476*da0073e9SAndroid Build Coastguard Worker // For example, with uint8, this allows for `a - b` to be treated as
477*da0073e9SAndroid Build Coastguard Worker // `a + 255 * b`.
478*da0073e9SAndroid Build Coastguard Worker if (!strict_unsigned) {
479*da0073e9SAndroid Build Coastguard Worker return greater_than_max<To>(f) ||
480*da0073e9SAndroid Build Coastguard Worker (c10::is_negative(f) &&
481*da0073e9SAndroid Build Coastguard Worker -static_cast<uint64_t>(f) > static_cast<uint64_t>(limit::max()));
482*da0073e9SAndroid Build Coastguard Worker }
483*da0073e9SAndroid Build Coastguard Worker }
484*da0073e9SAndroid Build Coastguard Worker return c10::less_than_lowest<To>(f) || greater_than_max<To>(f);
485*da0073e9SAndroid Build Coastguard Worker }
486*da0073e9SAndroid Build Coastguard Worker
487*da0073e9SAndroid Build Coastguard Worker template <typename To, typename From>
488*da0073e9SAndroid Build Coastguard Worker std::enable_if_t<std::is_floating_point_v<From>, bool> overflows(
489*da0073e9SAndroid Build Coastguard Worker From f,
490*da0073e9SAndroid Build Coastguard Worker bool strict_unsigned [[maybe_unused]] = false) {
491*da0073e9SAndroid Build Coastguard Worker using limit = std::numeric_limits<typename scalar_value_type<To>::type>;
492*da0073e9SAndroid Build Coastguard Worker if (limit::has_infinity && std::isinf(static_cast<double>(f))) {
493*da0073e9SAndroid Build Coastguard Worker return false;
494*da0073e9SAndroid Build Coastguard Worker }
495*da0073e9SAndroid Build Coastguard Worker if (!limit::has_quiet_NaN && (f != f)) {
496*da0073e9SAndroid Build Coastguard Worker return true;
497*da0073e9SAndroid Build Coastguard Worker }
498*da0073e9SAndroid Build Coastguard Worker return f < limit::lowest() || f > limit::max();
499*da0073e9SAndroid Build Coastguard Worker }
500*da0073e9SAndroid Build Coastguard Worker
501*da0073e9SAndroid Build Coastguard Worker C10_CLANG_DIAGNOSTIC_POP()
502*da0073e9SAndroid Build Coastguard Worker
503*da0073e9SAndroid Build Coastguard Worker #ifdef _MSC_VER
504*da0073e9SAndroid Build Coastguard Worker #pragma warning(pop)
505*da0073e9SAndroid Build Coastguard Worker #endif
506*da0073e9SAndroid Build Coastguard Worker
507*da0073e9SAndroid Build Coastguard Worker template <typename To, typename From>
508*da0073e9SAndroid Build Coastguard Worker std::enable_if_t<is_complex<From>::value, bool> overflows(
509*da0073e9SAndroid Build Coastguard Worker From f,
510*da0073e9SAndroid Build Coastguard Worker bool strict_unsigned = false) {
511*da0073e9SAndroid Build Coastguard Worker // casts from complex to real are considered to overflow if the
512*da0073e9SAndroid Build Coastguard Worker // imaginary component is non-zero
513*da0073e9SAndroid Build Coastguard Worker if (!is_complex<To>::value && f.imag() != 0) {
514*da0073e9SAndroid Build Coastguard Worker return true;
515*da0073e9SAndroid Build Coastguard Worker }
516*da0073e9SAndroid Build Coastguard Worker // Check for overflow componentwise
517*da0073e9SAndroid Build Coastguard Worker // (Technically, the imag overflow check is guaranteed to be false
518*da0073e9SAndroid Build Coastguard Worker // when !is_complex<To>, but any optimizer worth its salt will be
519*da0073e9SAndroid Build Coastguard Worker // able to figure it out.)
520*da0073e9SAndroid Build Coastguard Worker return overflows<
521*da0073e9SAndroid Build Coastguard Worker typename scalar_value_type<To>::type,
522*da0073e9SAndroid Build Coastguard Worker typename From::value_type>(f.real(), strict_unsigned) ||
523*da0073e9SAndroid Build Coastguard Worker overflows<
524*da0073e9SAndroid Build Coastguard Worker typename scalar_value_type<To>::type,
525*da0073e9SAndroid Build Coastguard Worker typename From::value_type>(f.imag(), strict_unsigned);
526*da0073e9SAndroid Build Coastguard Worker }
527*da0073e9SAndroid Build Coastguard Worker
528*da0073e9SAndroid Build Coastguard Worker C10_API inline std::ostream& operator<<(std::ostream& out, const Half& value) {
529*da0073e9SAndroid Build Coastguard Worker out << (float)value;
530*da0073e9SAndroid Build Coastguard Worker return out;
531*da0073e9SAndroid Build Coastguard Worker }
532*da0073e9SAndroid Build Coastguard Worker
533*da0073e9SAndroid Build Coastguard Worker } // namespace c10
534*da0073e9SAndroid Build Coastguard Worker
535*da0073e9SAndroid Build Coastguard Worker #include <c10/util/Half-inl.h> // IWYU pragma: keep
536