ggml-impl.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. #pragma once
  2. // GGML internal header
  3. #include "ggml.h"
  4. #include "gguf.h"
  5. #include <assert.h>
  6. #include <math.h>
  7. #include <stdlib.h> // load `stdlib.h` before other headers to work around MinGW bug: https://sourceforge.net/p/mingw-w64/bugs/192/
  8. #include <stdbool.h>
  9. #include <stdint.h>
  10. #include <string.h>
  11. #ifdef __ARM_FEATURE_SVE
  12. #include <arm_sve.h>
  13. #endif // __ARM_FEATURE_SVE
  14. #if defined(__ARM_NEON) && !defined(__CUDACC__) && !defined(__MUSACC__)
  15. // if YCM cannot find <arm_neon.h>, make a symbolic link to it, for example:
  16. //
  17. // $ ln -sfn /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include/arm_neon.h ./src/
  18. //
  19. #include <arm_neon.h>
  20. #endif
  21. #if defined(__F16C__)
  22. #include <immintrin.h>
  23. #endif
  24. #ifdef __cplusplus
  25. extern "C" {
  26. #endif
  27. void ggml_print_backtrace(void);
  28. #ifndef MIN
  29. # define MIN(a, b) ((a) < (b) ? (a) : (b))
  30. #endif
  31. #ifndef MAX
  32. # define MAX(a, b) ((a) > (b) ? (a) : (b))
  33. #endif
  34. // required for mmap as gguf only guarantees 32-byte alignment
  35. #define TENSOR_ALIGNMENT 32
  36. // static_assert should be a #define, but if it's not,
  37. // fall back to the _Static_assert C11 keyword.
  38. // if C99 - static_assert is noop
  39. // ref: https://stackoverflow.com/a/53923785/4039976
  40. #ifndef __cplusplus
  41. #ifndef static_assert
  42. #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L)
  43. #define static_assert(cond, msg) _Static_assert(cond, msg)
  44. #else
  45. #define static_assert(cond, msg) struct global_scope_noop_trick
  46. #endif
  47. #endif
  48. #endif
  49. static inline int ggml_up32(int n) {
  50. return (n + 31) & ~31;
  51. }
  52. //static inline int ggml_up64(int n) {
  53. // return (n + 63) & ~63;
  54. //}
  55. static inline int ggml_up(int n, int m) {
  56. // assert m is a power of 2
  57. GGML_ASSERT((m & (m - 1)) == 0);
  58. return (n + m - 1) & ~(m - 1);
  59. }
  60. //
  61. // logging
  62. //
  63. GGML_ATTRIBUTE_FORMAT(2, 3)
  64. GGML_API void ggml_log_internal (enum ggml_log_level level, const char * format, ...);
  65. GGML_API void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data);
  66. #define GGML_LOG(...) ggml_log_internal(GGML_LOG_LEVEL_NONE , __VA_ARGS__)
  67. #define GGML_LOG_INFO(...) ggml_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  68. #define GGML_LOG_WARN(...) ggml_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  69. #define GGML_LOG_ERROR(...) ggml_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  70. #define GGML_LOG_DEBUG(...) ggml_log_internal(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__)
  71. #define GGML_LOG_CONT(...) ggml_log_internal(GGML_LOG_LEVEL_CONT , __VA_ARGS__)
  72. #define GGML_DEBUG 0
  73. #if (GGML_DEBUG >= 1)
  74. #define GGML_PRINT_DEBUG(...) GGML_LOG_DEBUG(__VA_ARGS__)
  75. #else
  76. #define GGML_PRINT_DEBUG(...)
  77. #endif
  78. #if (GGML_DEBUG >= 5)
  79. #define GGML_PRINT_DEBUG_5(...) GGML_LOG_DEBUG(__VA_ARGS__)
  80. #else
  81. #define GGML_PRINT_DEBUG_5(...)
  82. #endif
  83. #if (GGML_DEBUG >= 10)
  84. #define GGML_PRINT_DEBUG_10(...) GGML_LOG_DEBUG(__VA_ARGS__)
  85. #else
  86. #define GGML_PRINT_DEBUG_10(...)
  87. #endif
  88. // tensor params
  89. static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) {
  90. GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings
  91. assert(params_size <= GGML_MAX_OP_PARAMS);
  92. memcpy(tensor->op_params, params, params_size);
  93. }
  94. static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
  95. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  96. return ((const int32_t *)(tensor->op_params))[i];
  97. }
  98. static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) {
  99. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  100. return ((const float *)(tensor->op_params))[i];
  101. }
  102. static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) {
  103. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  104. ((int32_t *)(tensor->op_params))[i] = value;
  105. }
  106. static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) {
  107. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  108. ((float *)(tensor->op_params))[i] = value;
  109. }
  110. struct ggml_map_custom1_op_params {
  111. ggml_custom1_op_t fun;
  112. int n_tasks;
  113. void * userdata;
  114. };
  115. struct ggml_map_custom2_op_params {
  116. ggml_custom2_op_t fun;
  117. int n_tasks;
  118. void * userdata;
  119. };
  120. struct ggml_map_custom3_op_params {
  121. ggml_custom3_op_t fun;
  122. int n_tasks;
  123. void * userdata;
  124. };
  125. struct ggml_custom_op_params {
  126. ggml_custom_op_t fun;
  127. int n_tasks;
  128. void * userdata;
  129. };
  130. // bitset
  131. typedef uint32_t ggml_bitset_t;
  132. static_assert(sizeof(ggml_bitset_t) == 4, "bitset_t constants must be updated");
  133. #define BITSET_SHR 5 // log2(sizeof(ggml_bitset_t)*8)
  134. #define BITSET_MASK (sizeof(ggml_bitset_t)*8 - 1)
  135. static size_t ggml_bitset_size(size_t n) {
  136. return (n + BITSET_MASK) >> BITSET_SHR;
  137. }
  138. static inline bool ggml_bitset_get(const ggml_bitset_t * bitset, size_t i) {
  139. return !!(bitset[i >> BITSET_SHR] & (1u << (i & BITSET_MASK)));
  140. }
  141. static inline void ggml_bitset_set(ggml_bitset_t * bitset, size_t i) {
  142. bitset[i >> BITSET_SHR] |= (1u << (i & BITSET_MASK));
  143. }
  144. static inline void ggml_bitset_clear(ggml_bitset_t * bitset, size_t i) {
  145. bitset[i >> BITSET_SHR] &= ~(1u << (i & BITSET_MASK));
  146. }
  147. // hash set
  148. #define GGML_HASHSET_FULL ((size_t)-1)
  149. #define GGML_HASHSET_ALREADY_EXISTS ((size_t)-2)
  150. struct ggml_hash_set {
  151. size_t size;
  152. ggml_bitset_t * used; // whether or not the keys are in use i.e. set
  153. struct ggml_tensor ** keys; // actual tensors in the set, keys[i] is only defined if ggml_bitset_get(used, i)
  154. };
  155. struct ggml_hash_set ggml_hash_set_new(size_t size);
  156. void ggml_hash_set_free(struct ggml_hash_set * hash_set);
  157. // returns the minimum size for a hash set that can hold min_sz elements
  158. size_t ggml_hash_size(size_t min_sz);
  159. // remove all elements from the hash set
  160. void ggml_hash_set_reset(struct ggml_hash_set * hash_set);
  161. // returns true if key is in the hash set
  162. static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  163. // returns GGML_HASHSET_FULL if table is full, otherwise the current index of the key or where it should be inserted
  164. static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key);
  165. // returns GGML_HASHSET_ALREADY_EXISTS if key already exists, index otherwise, asserts if table is full
  166. static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  167. // return index, asserts if table is full
  168. static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  169. // hash function for ggml_tensor
  170. static inline size_t ggml_hash(const struct ggml_tensor * p) {
  171. // the last 4 bits are always zero due to alignment
  172. return (size_t)(uintptr_t)p >> 4;
  173. }
  174. static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key) {
  175. size_t h = ggml_hash(key) % hash_set->size;
  176. // linear probing
  177. size_t i = h;
  178. while (ggml_bitset_get(hash_set->used, i) && hash_set->keys[i] != key) {
  179. i = (i + 1) % hash_set->size;
  180. if (i == h) {
  181. // visited all hash table entries -> not found
  182. return GGML_HASHSET_FULL;
  183. }
  184. }
  185. return i;
  186. }
  187. static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  188. size_t i = ggml_hash_find(hash_set, key);
  189. return i != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, i);
  190. }
  191. static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  192. size_t h = ggml_hash(key) % hash_set->size;
  193. // linear probing
  194. size_t i = h;
  195. do {
  196. if (!ggml_bitset_get(hash_set->used, i)) {
  197. ggml_bitset_set(hash_set->used, i);
  198. hash_set->keys[i] = key;
  199. return i;
  200. }
  201. if (hash_set->keys[i] == key) {
  202. return GGML_HASHSET_ALREADY_EXISTS;
  203. }
  204. i = (i + 1) % hash_set->size;
  205. } while (i != h);
  206. // visited all hash table entries -> not found
  207. GGML_ABORT("fatal error");
  208. }
  209. static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  210. size_t h = ggml_hash(key) % hash_set->size;
  211. // linear probing
  212. size_t i = h;
  213. do {
  214. if (!ggml_bitset_get(hash_set->used, i)) {
  215. ggml_bitset_set(hash_set->used, i);
  216. hash_set->keys[i] = key;
  217. return i;
  218. }
  219. if (hash_set->keys[i] == key) {
  220. return i;
  221. }
  222. i = (i + 1) % hash_set->size;
  223. } while (i != h);
  224. // visited all hash table entries -> not found
  225. GGML_ABORT("fatal error");
  226. }
  227. // computation graph
  228. enum ggml_cgraph_eval_order {
  229. GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT = 0,
  230. GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT,
  231. GGML_CGRAPH_EVAL_ORDER_COUNT
  232. };
  233. struct ggml_cgraph {
  234. int size; // maximum number of nodes/leafs/grads/grad_accs
  235. int n_nodes; // number of nodes currently in use
  236. int n_leafs; // number of leafs currently in use
  237. struct ggml_tensor ** nodes; // tensors with data that can change if the graph is evaluated
  238. struct ggml_tensor ** grads; // the outputs of these tensors are the gradients of the nodes
  239. struct ggml_tensor ** grad_accs; // accumulators for node gradients
  240. struct ggml_tensor ** leafs; // tensors with constant data
  241. struct ggml_hash_set visited_hash_set;
  242. enum ggml_cgraph_eval_order order;
  243. };
  244. // returns a slice of cgraph with nodes [i0, i1)
  245. // the slice does not have leafs or gradients
  246. // if you need the gradients, get them from the original graph
  247. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph, int i0, int i1);
  248. // Memory allocation
  249. GGML_API void * ggml_aligned_malloc(size_t size);
  250. GGML_API void ggml_aligned_free(void * ptr, size_t size);
  251. // FP16 to FP32 conversion
  252. // 16-bit float
  253. // on Arm, we use __fp16
  254. // on x86, we use uint16_t
  255. //
  256. // for old CUDA compilers (<= 11), we use uint16_t: ref https://github.com/ggml-org/llama.cpp/pull/10616
  257. // for MUSA compilers , we use uint16_t: ref https://github.com/ggml-org/llama.cpp/pull/11843
  258. //
  259. #if defined(__ARM_NEON) && !(defined(__CUDACC__) && __CUDACC_VER_MAJOR__ <= 11) && !defined(__MUSACC__)
  260. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  261. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  262. #define GGML_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  263. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  264. __fp16 tmp;
  265. memcpy(&tmp, &h, sizeof(ggml_fp16_t));
  266. return (float)tmp;
  267. }
  268. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  269. ggml_fp16_t res;
  270. __fp16 tmp = f;
  271. memcpy(&res, &tmp, sizeof(ggml_fp16_t));
  272. return res;
  273. }
  274. #elif defined(__F16C__)
  275. #ifdef _MSC_VER
  276. #define GGML_COMPUTE_FP16_TO_FP32(x) _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(x)))
  277. #define GGML_COMPUTE_FP32_TO_FP16(x) _mm_extract_epi16(_mm_cvtps_ph(_mm_set_ss(x), 0), 0)
  278. #else
  279. #define GGML_COMPUTE_FP16_TO_FP32(x) _cvtsh_ss(x)
  280. #define GGML_COMPUTE_FP32_TO_FP16(x) _cvtss_sh(x, 0)
  281. #endif
  282. #elif defined(__POWER9_VECTOR__)
  283. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  284. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  285. /* the inline asm below is about 12% faster than the lookup method */
  286. #define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x)
  287. #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
  288. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  289. float f;
  290. double d;
  291. __asm__(
  292. "mtfprd %0,%2\n"
  293. "xscvhpdp %0,%0\n"
  294. "frsp %1,%0\n" :
  295. /* temp */ "=d"(d),
  296. /* out */ "=f"(f):
  297. /* in */ "r"(h));
  298. return f;
  299. }
  300. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  301. double d;
  302. ggml_fp16_t r;
  303. __asm__( /* xscvdphp can work on double or single precision */
  304. "xscvdphp %0,%2\n"
  305. "mffprd %1,%0\n" :
  306. /* temp */ "=d"(d),
  307. /* out */ "=r"(r):
  308. /* in */ "f"(f));
  309. return r;
  310. }
  311. #elif defined(__riscv) && defined(__riscv_zfhmin)
  312. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  313. float f;
  314. __asm__(
  315. "fmv.h.x %[f], %[h]\n\t"
  316. "fcvt.s.h %[f], %[f]"
  317. : [f] "=&f" (f)
  318. : [h] "r" (h)
  319. );
  320. return f;
  321. }
  322. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  323. ggml_fp16_t res;
  324. __asm__(
  325. "fcvt.h.s %[f], %[f]\n\t"
  326. "fmv.x.h %[h], %[f]"
  327. : [h] "=&r" (res)
  328. : [f] "f" (f)
  329. );
  330. return res;
  331. }
  332. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  333. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  334. #define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x)
  335. #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
  336. #else
  337. // FP16 <-> FP32
  338. // ref: https://github.com/Maratyszcza/FP16
  339. static inline float fp32_from_bits(uint32_t w) {
  340. union {
  341. uint32_t as_bits;
  342. float as_value;
  343. } fp32;
  344. fp32.as_bits = w;
  345. return fp32.as_value;
  346. }
  347. static inline uint32_t fp32_to_bits(float f) {
  348. union {
  349. float as_value;
  350. uint32_t as_bits;
  351. } fp32;
  352. fp32.as_value = f;
  353. return fp32.as_bits;
  354. }
  355. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  356. const uint32_t w = (uint32_t) h << 16;
  357. const uint32_t sign = w & UINT32_C(0x80000000);
  358. const uint32_t two_w = w + w;
  359. const uint32_t exp_offset = UINT32_C(0xE0) << 23;
  360. #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
  361. const float exp_scale = 0x1.0p-112f;
  362. #else
  363. const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
  364. #endif
  365. const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
  366. const uint32_t magic_mask = UINT32_C(126) << 23;
  367. const float magic_bias = 0.5f;
  368. const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
  369. const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
  370. const uint32_t result = sign |
  371. (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
  372. return fp32_from_bits(result);
  373. }
  374. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  375. #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
  376. const float scale_to_inf = 0x1.0p+112f;
  377. const float scale_to_zero = 0x1.0p-110f;
  378. #else
  379. const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
  380. const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
  381. #endif
  382. float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
  383. const uint32_t w = fp32_to_bits(f);
  384. const uint32_t shl1_w = w + w;
  385. const uint32_t sign = w & UINT32_C(0x80000000);
  386. uint32_t bias = shl1_w & UINT32_C(0xFF000000);
  387. if (bias < UINT32_C(0x71000000)) {
  388. bias = UINT32_C(0x71000000);
  389. }
  390. base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
  391. const uint32_t bits = fp32_to_bits(base);
  392. const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
  393. const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
  394. const uint32_t nonsign = exp_bits + mantissa_bits;
  395. return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
  396. }
  397. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  398. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  399. #endif // defined(__ARM_NEON) && !(defined(__CUDACC__) && __CUDACC_VER_MAJOR__ <= 11) && !defined(__MUSACC__)
  400. // precomputed f32 table for f16 (256 KB)
  401. // defined in ggml.c, initialized in ggml_init()
  402. GGML_API float ggml_table_f32_f16[1 << 16];
  403. // On ARM NEON, it's quicker to directly convert x -> x instead of calling into ggml_lookup_fp16_to_fp32,
  404. // so we define GGML_FP16_TO_FP32 and GGML_FP32_TO_FP16 elsewhere for NEON.
  405. // This is also true for POWER9.
  406. #if !defined(GGML_FP16_TO_FP32)
  407. inline static float ggml_lookup_fp16_to_fp32(ggml_fp16_t f) {
  408. uint16_t s;
  409. memcpy(&s, &f, sizeof(uint16_t));
  410. return ggml_table_f32_f16[s];
  411. }
  412. #define GGML_FP16_TO_FP32(x) ggml_lookup_fp16_to_fp32(x)
  413. #endif
  414. #if !defined(GGML_FP32_TO_FP16)
  415. #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
  416. #endif
  417. /**
  418. * Converts brain16 to float32.
  419. *
  420. * The bfloat16 floating point format has the following structure:
  421. *
  422. * ┌sign
  423. * │
  424. * │ ┌exponent
  425. * │ │
  426. * │ │ ┌mantissa
  427. * │ │ │
  428. * │┌──┴───┐┌─┴───┐
  429. * 0b0000000000000000 brain16
  430. *
  431. * Since bf16 has the same number of exponent bits as a 32bit float,
  432. * encoding and decoding numbers becomes relatively straightforward.
  433. *
  434. * ┌sign
  435. * │
  436. * │ ┌exponent
  437. * │ │
  438. * │ │ ┌mantissa
  439. * │ │ │
  440. * │┌──┴───┐┌─┴───────────────────┐
  441. * 0b00000000000000000000000000000000 IEEE binary32
  442. *
  443. * For comparison, the standard fp16 format has fewer exponent bits.
  444. *
  445. * ┌sign
  446. * │
  447. * │ ┌exponent
  448. * │ │
  449. * │ │ ┌mantissa
  450. * │ │ │
  451. * │┌─┴─┐┌─┴──────┐
  452. * 0b0000000000000000 IEEE binary16
  453. *
  454. * @see IEEE 754-2008
  455. */
  456. static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
  457. union {
  458. float f;
  459. uint32_t i;
  460. } u;
  461. u.i = (uint32_t)h.bits << 16;
  462. return u.f;
  463. }
  464. /**
  465. * Converts float32 to brain16.
  466. *
  467. * This is binary identical with Google Brain float conversion.
  468. * Floats shall round to nearest even, and NANs shall be quiet.
  469. * Subnormals aren't flushed to zero, except perhaps when used.
  470. * This code should vectorize nicely if using modern compilers.
  471. */
  472. static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) {
  473. ggml_bf16_t h;
  474. union {
  475. float f;
  476. uint32_t i;
  477. } u;
  478. u.f = s;
  479. if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */
  480. h.bits = (u.i >> 16) | 64; /* force to quiet */
  481. return h;
  482. }
  483. h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16;
  484. return h;
  485. }
  486. #define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x)
  487. #define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x)
  488. #ifdef __cplusplus
  489. }
  490. #endif
  491. #ifdef __cplusplus
  492. #include <vector>
  493. // expose GGUF internals for test code
  494. GGML_API size_t gguf_type_size(enum gguf_type type);
  495. GGML_API struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params);
  496. GGML_API void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta);
  497. #endif // __cplusplus