ggml-impl.h 19 KB

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