ggml-impl.h 19 KB

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