ggml-impl.h 19 KB

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