|
17 | 17 | #define MIN(a, b) ((a) < (b) ? (a) : (b)) |
18 | 18 | #define MAX(a, b) ((a) > (b) ? (a) : (b)) |
19 | 19 |
|
| 20 | +/** |
| 21 | + * Converts brain16 to float32. |
| 22 | + * |
| 23 | + * The bfloat16 floating point format has the following structure: |
| 24 | + * |
| 25 | + * ┌sign |
| 26 | + * │ |
| 27 | + * │ ┌exponent |
| 28 | + * │ │ |
| 29 | + * │ │ ┌mantissa |
| 30 | + * │ │ │ |
| 31 | + * │┌──┴───┐┌─┴───┐ |
| 32 | + * 0b0000000000000000 brain16 |
| 33 | + * |
| 34 | + * Since bf16 has the same number of exponent bits as a 32bit float, |
| 35 | + * encoding and decoding numbers becomes relatively straightforward. |
| 36 | + * |
| 37 | + * ┌sign |
| 38 | + * │ |
| 39 | + * │ ┌exponent |
| 40 | + * │ │ |
| 41 | + * │ │ ┌mantissa |
| 42 | + * │ │ │ |
| 43 | + * │┌──┴───┐┌─┴───────────────────┐ |
| 44 | + * 0b00000000000000000000000000000000 IEEE binary32 |
| 45 | + * |
| 46 | + * For comparison, the standard fp16 format has fewer exponent bits. |
| 47 | + * |
| 48 | + * ┌sign |
| 49 | + * │ |
| 50 | + * │ ┌exponent |
| 51 | + * │ │ |
| 52 | + * │ │ ┌mantissa |
| 53 | + * │ │ │ |
| 54 | + * │┌─┴─┐┌─┴──────┐ |
| 55 | + * 0b0000000000000000 IEEE binary16 |
| 56 | + * |
| 57 | + * @see IEEE 754-2008 |
| 58 | + */ |
| 59 | +static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) { |
| 60 | + union { |
| 61 | + float f; |
| 62 | + uint32_t i; |
| 63 | + } u; |
| 64 | + u.i = (uint32_t)h.bits << 16; |
| 65 | + return u.f; |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * Converts float32 to brain16. |
| 70 | + * |
| 71 | + * This function is binary identical to AMD Zen4 VCVTNEPS2BF16. |
| 72 | + * Subnormals shall be flushed to zero, and NANs will be quiet. |
| 73 | + * This code should vectorize nicely if using modern compilers. |
| 74 | + */ |
| 75 | +static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) { |
| 76 | + ggml_bf16_t h; |
| 77 | + union { |
| 78 | + float f; |
| 79 | + uint32_t i; |
| 80 | + } u; |
| 81 | + u.f = s; |
| 82 | + if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */ |
| 83 | + h.bits = (u.i >> 16) | 64; /* force to quiet */ |
| 84 | + return h; |
| 85 | + } |
| 86 | + if (!(u.i & 0x7f800000)) { /* subnormal */ |
| 87 | + h.bits = (u.i & 0x80000000) >> 16; /* flush to zero */ |
| 88 | + return h; |
| 89 | + } |
| 90 | + h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16; |
| 91 | + return h; |
| 92 | +} |
| 93 | + |
| 94 | +#define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x) |
| 95 | +#define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x) |
| 96 | + |
20 | 97 | #ifdef __cplusplus |
21 | 98 | extern "C" { |
22 | 99 | #endif |
|
0 commit comments