ggml-impl.h 20 KB

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