ggml-impl.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. // TODO: move to ggml.h? (won't be able to inline)
  61. static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
  62. if (a->type != b->type) {
  63. return false;
  64. }
  65. for (int i = 0; i < GGML_MAX_DIMS; i++) {
  66. if (a->ne[i] != b->ne[i]) {
  67. return false;
  68. }
  69. if (a->nb[i] != b->nb[i]) {
  70. return false;
  71. }
  72. }
  73. return true;
  74. }
  75. static bool ggml_op_is_empty(enum ggml_op op) {
  76. switch (op) {
  77. case GGML_OP_NONE:
  78. case GGML_OP_RESHAPE:
  79. case GGML_OP_TRANSPOSE:
  80. case GGML_OP_VIEW:
  81. case GGML_OP_PERMUTE:
  82. return true;
  83. default:
  84. return false;
  85. }
  86. }
  87. static inline float ggml_softplus(float input) {
  88. return (input > 20.0f) ? input : logf(1 + expf(input));
  89. }
  90. //
  91. // logging
  92. //
  93. GGML_ATTRIBUTE_FORMAT(2, 3)
  94. GGML_API void ggml_log_internal (enum ggml_log_level level, const char * format, ...);
  95. GGML_API void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data);
  96. #define GGML_LOG(...) ggml_log_internal(GGML_LOG_LEVEL_NONE , __VA_ARGS__)
  97. #define GGML_LOG_INFO(...) ggml_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
  98. #define GGML_LOG_WARN(...) ggml_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
  99. #define GGML_LOG_ERROR(...) ggml_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
  100. #define GGML_LOG_DEBUG(...) ggml_log_internal(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__)
  101. #define GGML_LOG_CONT(...) ggml_log_internal(GGML_LOG_LEVEL_CONT , __VA_ARGS__)
  102. #define GGML_DEBUG 0
  103. #if (GGML_DEBUG >= 1)
  104. #define GGML_PRINT_DEBUG(...) GGML_LOG_DEBUG(__VA_ARGS__)
  105. #else
  106. #define GGML_PRINT_DEBUG(...)
  107. #endif
  108. #if (GGML_DEBUG >= 5)
  109. #define GGML_PRINT_DEBUG_5(...) GGML_LOG_DEBUG(__VA_ARGS__)
  110. #else
  111. #define GGML_PRINT_DEBUG_5(...)
  112. #endif
  113. #if (GGML_DEBUG >= 10)
  114. #define GGML_PRINT_DEBUG_10(...) GGML_LOG_DEBUG(__VA_ARGS__)
  115. #else
  116. #define GGML_PRINT_DEBUG_10(...)
  117. #endif
  118. // tensor params
  119. static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) {
  120. GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings
  121. assert(params_size <= GGML_MAX_OP_PARAMS);
  122. memcpy(tensor->op_params, params, params_size);
  123. }
  124. static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
  125. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  126. return ((const int32_t *)(tensor->op_params))[i];
  127. }
  128. static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) {
  129. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  130. return ((const float *)(tensor->op_params))[i];
  131. }
  132. static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) {
  133. assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
  134. ((int32_t *)(tensor->op_params))[i] = value;
  135. }
  136. static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) {
  137. assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
  138. ((float *)(tensor->op_params))[i] = value;
  139. }
  140. struct ggml_map_custom1_op_params {
  141. ggml_custom1_op_t fun;
  142. int n_tasks;
  143. void * userdata;
  144. };
  145. struct ggml_map_custom2_op_params {
  146. ggml_custom2_op_t fun;
  147. int n_tasks;
  148. void * userdata;
  149. };
  150. struct ggml_map_custom3_op_params {
  151. ggml_custom3_op_t fun;
  152. int n_tasks;
  153. void * userdata;
  154. };
  155. struct ggml_custom_op_params {
  156. ggml_custom_op_t fun;
  157. int n_tasks;
  158. void * userdata;
  159. };
  160. // bitset
  161. typedef uint32_t ggml_bitset_t;
  162. static_assert(sizeof(ggml_bitset_t) == 4, "bitset_t constants must be updated");
  163. #define BITSET_SHR 5 // log2(sizeof(ggml_bitset_t)*8)
  164. #define BITSET_MASK (sizeof(ggml_bitset_t)*8 - 1)
  165. static size_t ggml_bitset_size(size_t n) {
  166. return (n + BITSET_MASK) >> BITSET_SHR;
  167. }
  168. static inline bool ggml_bitset_get(const ggml_bitset_t * bitset, size_t i) {
  169. return !!(bitset[i >> BITSET_SHR] & (1u << (i & BITSET_MASK)));
  170. }
  171. static inline void ggml_bitset_set(ggml_bitset_t * bitset, size_t i) {
  172. bitset[i >> BITSET_SHR] |= (1u << (i & BITSET_MASK));
  173. }
  174. static inline void ggml_bitset_clear(ggml_bitset_t * bitset, size_t i) {
  175. bitset[i >> BITSET_SHR] &= ~(1u << (i & BITSET_MASK));
  176. }
  177. // hash set
  178. #define GGML_HASHSET_FULL ((size_t)-1)
  179. #define GGML_HASHSET_ALREADY_EXISTS ((size_t)-2)
  180. struct ggml_hash_set {
  181. size_t size;
  182. ggml_bitset_t * used; // whether or not the keys are in use i.e. set
  183. struct ggml_tensor ** keys; // actual tensors in the set, keys[i] is only defined if ggml_bitset_get(used, i)
  184. };
  185. struct ggml_hash_set ggml_hash_set_new(size_t size);
  186. void ggml_hash_set_free(struct ggml_hash_set * hash_set);
  187. // returns the minimum size for a hash set that can hold min_sz elements
  188. size_t ggml_hash_size(size_t min_sz);
  189. // remove all elements from the hash set
  190. void ggml_hash_set_reset(struct ggml_hash_set * hash_set);
  191. // returns true if key is in the hash set
  192. static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  193. // returns GGML_HASHSET_FULL if table is full, otherwise the current index of the key or where it should be inserted
  194. static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key);
  195. // returns GGML_HASHSET_ALREADY_EXISTS if key already exists, index otherwise, asserts if table is full
  196. static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  197. // return index, asserts if table is full
  198. static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
  199. // hash function for ggml_tensor
  200. static inline size_t ggml_hash(const struct ggml_tensor * p) {
  201. // the last 4 bits are always zero due to alignment
  202. return (size_t)(uintptr_t)p >> 4;
  203. }
  204. static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key) {
  205. size_t h = ggml_hash(key) % hash_set->size;
  206. // linear probing
  207. size_t i = h;
  208. while (ggml_bitset_get(hash_set->used, i) && hash_set->keys[i] != key) {
  209. i = (i + 1) % hash_set->size;
  210. if (i == h) {
  211. // visited all hash table entries -> not found
  212. return GGML_HASHSET_FULL;
  213. }
  214. }
  215. return i;
  216. }
  217. static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  218. size_t i = ggml_hash_find(hash_set, key);
  219. return i != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, i);
  220. }
  221. static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  222. size_t h = ggml_hash(key) % hash_set->size;
  223. // linear probing
  224. size_t i = h;
  225. do {
  226. if (!ggml_bitset_get(hash_set->used, i)) {
  227. ggml_bitset_set(hash_set->used, i);
  228. hash_set->keys[i] = key;
  229. return i;
  230. }
  231. if (hash_set->keys[i] == key) {
  232. return GGML_HASHSET_ALREADY_EXISTS;
  233. }
  234. i = (i + 1) % hash_set->size;
  235. } while (i != h);
  236. // visited all hash table entries -> not found
  237. GGML_ABORT("fatal error");
  238. }
  239. static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
  240. size_t h = ggml_hash(key) % hash_set->size;
  241. // linear probing
  242. size_t i = h;
  243. do {
  244. if (!ggml_bitset_get(hash_set->used, i)) {
  245. ggml_bitset_set(hash_set->used, i);
  246. hash_set->keys[i] = key;
  247. return i;
  248. }
  249. if (hash_set->keys[i] == key) {
  250. return i;
  251. }
  252. i = (i + 1) % hash_set->size;
  253. } while (i != h);
  254. // visited all hash table entries -> not found
  255. GGML_ABORT("fatal error");
  256. }
  257. // computation graph
  258. enum ggml_cgraph_eval_order {
  259. GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT = 0,
  260. GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT,
  261. GGML_CGRAPH_EVAL_ORDER_COUNT
  262. };
  263. struct ggml_cgraph {
  264. int size; // maximum number of nodes/leafs/grads/grad_accs
  265. int n_nodes; // number of nodes currently in use
  266. int n_leafs; // number of leafs currently in use
  267. struct ggml_tensor ** nodes; // tensors with data that can change if the graph is evaluated
  268. struct ggml_tensor ** grads; // the outputs of these tensors are the gradients of the nodes
  269. struct ggml_tensor ** grad_accs; // accumulators for node gradients
  270. struct ggml_tensor ** leafs; // tensors with constant data
  271. int32_t * use_counts;// number of uses of each tensor, indexed by hash table slot
  272. struct ggml_hash_set visited_hash_set;
  273. enum ggml_cgraph_eval_order order;
  274. };
  275. // returns a slice of cgraph with nodes [i0, i1)
  276. // the slice does not have leafs or gradients
  277. // if you need the gradients, get them from the original graph
  278. struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph, int i0, int i1);
  279. // ggml-alloc.c: true if the operation can reuse memory from its sources
  280. GGML_API bool ggml_op_can_inplace(enum ggml_op op);
  281. // Memory allocation
  282. GGML_API void * ggml_aligned_malloc(size_t size);
  283. GGML_API void ggml_aligned_free(void * ptr, size_t size);
  284. // FP16 <-> FP32
  285. // ref: https://github.com/Maratyszcza/FP16
  286. static inline float fp32_from_bits(uint32_t w) {
  287. union {
  288. uint32_t as_bits;
  289. float as_value;
  290. } fp32;
  291. fp32.as_bits = w;
  292. return fp32.as_value;
  293. }
  294. static inline uint32_t fp32_to_bits(float f) {
  295. union {
  296. float as_value;
  297. uint32_t as_bits;
  298. } fp32;
  299. fp32.as_value = f;
  300. return fp32.as_bits;
  301. }
  302. static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
  303. const uint32_t w = (uint32_t) h << 16;
  304. const uint32_t sign = w & UINT32_C(0x80000000);
  305. const uint32_t two_w = w + w;
  306. const uint32_t exp_offset = UINT32_C(0xE0) << 23;
  307. #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
  308. const float exp_scale = 0x1.0p-112f;
  309. #else
  310. const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
  311. #endif
  312. const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
  313. const uint32_t magic_mask = UINT32_C(126) << 23;
  314. const float magic_bias = 0.5f;
  315. const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
  316. const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
  317. const uint32_t result = sign |
  318. (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
  319. return fp32_from_bits(result);
  320. }
  321. static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
  322. #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
  323. const float scale_to_inf = 0x1.0p+112f;
  324. const float scale_to_zero = 0x1.0p-110f;
  325. #else
  326. const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
  327. const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
  328. #endif
  329. float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
  330. const uint32_t w = fp32_to_bits(f);
  331. const uint32_t shl1_w = w + w;
  332. const uint32_t sign = w & UINT32_C(0x80000000);
  333. uint32_t bias = shl1_w & UINT32_C(0xFF000000);
  334. if (bias < UINT32_C(0x71000000)) {
  335. bias = UINT32_C(0x71000000);
  336. }
  337. base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
  338. const uint32_t bits = fp32_to_bits(base);
  339. const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
  340. const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
  341. const uint32_t nonsign = exp_bits + mantissa_bits;
  342. return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
  343. }
  344. #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
  345. #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
  346. #define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x)
  347. #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
  348. static inline float ggml_e8m0_to_fp32(uint8_t x) {
  349. uint32_t bits; // Stores the raw bit representation of the float
  350. // Handle special case for minimum exponent (denormalized float)
  351. if (x == 0) {
  352. // Bit pattern for 2^(-127):
  353. // - Sign bit: 0 (positive)
  354. // - Exponent: 0 (denormalized number)
  355. // - Mantissa: 0x400000 (0.5 in fractional form)
  356. // Value = 0.5 * 2^(-126) = 2^(-127)
  357. bits = 0x00400000;
  358. }
  359. // note: disabled as we don't need to handle NaNs
  360. //// Handle special case for NaN (all bits set)
  361. //else if (x == 0xFF) {
  362. // // Standard quiet NaN pattern:
  363. // // - Sign bit: 0
  364. // // - Exponent: all 1s (0xFF)
  365. // // - Mantissa: 0x400000 (quiet NaN flag)
  366. // bits = 0x7FC00000;
  367. //}
  368. // Normalized values (most common case)
  369. else {
  370. // Construct normalized float by shifting exponent into position:
  371. // - Exponent field: 8 bits (positions 30-23)
  372. // - Mantissa: 0 (implicit leading 1)
  373. // Value = 2^(x - 127)
  374. bits = (uint32_t) x << 23;
  375. }
  376. float result; // Final float value
  377. // Safely reinterpret bit pattern as float without type-punning issues
  378. memcpy(&result, &bits, sizeof(float));
  379. return result;
  380. }
  381. // Equal to ggml_e8m0_to_fp32/2
  382. // Useful with MXFP4 quantization since the E0M2 values are doubled
  383. static inline float ggml_e8m0_to_fp32_half(uint8_t x) {
  384. uint32_t bits;
  385. // For x < 2: use precomputed denormal patterns
  386. if (x < 2) {
  387. // 0x00200000 = 2^(-128), 0x00400000 = 2^(-127)
  388. bits = 0x00200000 << x;
  389. }
  390. // For x >= 2: normalized exponent adjustment
  391. else {
  392. // 0.5 * 2^(x-127) = 2^(x-128) = normalized with exponent (x-1)
  393. bits = (uint32_t)(x - 1) << 23;
  394. }
  395. // Note: NaNs are not handled here
  396. float result;
  397. memcpy(&result, &bits, sizeof(float));
  398. return result;
  399. }
  400. #define GGML_E8M0_TO_FP32(x) ggml_e8m0_to_fp32(x)
  401. #define GGML_E8M0_TO_FP32_HALF(x) ggml_e8m0_to_fp32_half(x)
  402. /**
  403. * Converts brain16 to float32.
  404. *
  405. * The bfloat16 floating point format has the following structure:
  406. *
  407. * ┌sign
  408. * │
  409. * │ ┌exponent
  410. * │ │
  411. * │ │ ┌mantissa
  412. * │ │ │
  413. * │┌──┴───┐┌─┴───┐
  414. * 0b0000000000000000 brain16
  415. *
  416. * Since bf16 has the same number of exponent bits as a 32bit float,
  417. * encoding and decoding numbers becomes relatively straightforward.
  418. *
  419. * ┌sign
  420. * │
  421. * │ ┌exponent
  422. * │ │
  423. * │ │ ┌mantissa
  424. * │ │ │
  425. * │┌──┴───┐┌─┴───────────────────┐
  426. * 0b00000000000000000000000000000000 IEEE binary32
  427. *
  428. * For comparison, the standard fp16 format has fewer exponent bits.
  429. *
  430. * ┌sign
  431. * │
  432. * │ ┌exponent
  433. * │ │
  434. * │ │ ┌mantissa
  435. * │ │ │
  436. * │┌─┴─┐┌─┴──────┐
  437. * 0b0000000000000000 IEEE binary16
  438. *
  439. * @see IEEE 754-2008
  440. */
  441. static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
  442. union {
  443. float f;
  444. uint32_t i;
  445. } u;
  446. u.i = (uint32_t)h.bits << 16;
  447. return u.f;
  448. }
  449. /**
  450. * Converts float32 to brain16.
  451. *
  452. * This is binary identical with Google Brain float conversion.
  453. * Floats shall round to nearest even, and NANs shall be quiet.
  454. * Subnormals aren't flushed to zero, except perhaps when used.
  455. * This code should vectorize nicely if using modern compilers.
  456. */
  457. static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) {
  458. ggml_bf16_t h;
  459. union {
  460. float f;
  461. uint32_t i;
  462. } u;
  463. u.f = s;
  464. if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */
  465. h.bits = (u.i >> 16) | 64; /* force to quiet */
  466. return h;
  467. }
  468. h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16;
  469. return h;
  470. }
  471. #define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x)
  472. #define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x)
  473. // return true if the node's results are only used by N other nodes
  474. // and can be fused into their calculations.
  475. static inline bool ggml_node_has_n_uses(const struct ggml_cgraph * cgraph, int node_idx, int32_t n_uses) {
  476. const struct ggml_tensor * node = cgraph->nodes[node_idx];
  477. // check the use count against how many we're replacing
  478. size_t hash_pos = ggml_hash_find(&cgraph->visited_hash_set, node);
  479. if (!ggml_bitset_get(cgraph->visited_hash_set.used, hash_pos) || cgraph->use_counts[hash_pos] != n_uses) {
  480. return false;
  481. }
  482. // if node is a view, some other node might be using the intermediate result
  483. // via the view source.
  484. if (node->view_src) {
  485. return false;
  486. }
  487. // If the user requested output for the node, can't fuse
  488. if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
  489. return false;
  490. }
  491. return true;
  492. }
  493. // Returns true if nodes with indices { node_idxs } are the sequence of ggml_ops in ops[]
  494. // and are fusable. Nodes are considered fusable according to this function if:
  495. // - all nodes except the last have only one use and are not views/outputs (see ggml_node_has_N_uses).
  496. // - all nodes except the last are a src of the following node.
  497. // - all nodes are the same shape.
  498. // TODO: Consider allowing GGML_OP_NONE nodes in between
  499. static inline bool ggml_can_fuse_ext(const struct ggml_cgraph * cgraph, const int * node_idxs, const enum ggml_op * ops, int num_ops) {
  500. for (int i = 0; i < num_ops; ++i) {
  501. if (node_idxs[i] >= cgraph->n_nodes) {
  502. return false;
  503. }
  504. struct ggml_tensor * node = cgraph->nodes[node_idxs[i]];
  505. if (node->op != ops[i]) {
  506. return false;
  507. }
  508. if (i < num_ops - 1 && !ggml_node_has_n_uses(cgraph, node_idxs[i], 1)) {
  509. return false;
  510. }
  511. if (i > 0) {
  512. struct ggml_tensor * prev = cgraph->nodes[node_idxs[i - 1]];
  513. if (node->src[0] != prev && node->src[1] != prev) {
  514. return false;
  515. }
  516. if (!ggml_are_same_shape(node, prev)) {
  517. return false;
  518. }
  519. }
  520. }
  521. return true;
  522. }
  523. // same as above, for sequential indices starting at node_idx
  524. static inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, const enum ggml_op * ops, int num_ops) {
  525. assert(num_ops < 32);
  526. if (node_idx + num_ops > cgraph->n_nodes) {
  527. return false;
  528. }
  529. int idxs[32];
  530. for (int i = 0; i < num_ops; ++i) {
  531. idxs[i] = node_idx + i;
  532. }
  533. return ggml_can_fuse_ext(cgraph, idxs, ops, num_ops);
  534. }
  535. #ifdef __cplusplus
  536. }
  537. #endif
  538. #ifdef __cplusplus
  539. #include <initializer_list>
  540. #include <vector>
  541. // nicer C++ syntax for ggml_can_fuse
  542. inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
  543. return ggml_can_fuse(cgraph, node_idx, ops.begin(), (int)ops.size());
  544. }
  545. // expose GGUF internals for test code
  546. GGML_API size_t gguf_type_size(enum gguf_type type);
  547. GGML_API struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params);
  548. GGML_API void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta);
  549. #endif // __cplusplus