Debian Codegraph @

external/whispercpp/ggml-impl.h

raw
1 #pragma once
2
3 // GGML internal header
4
5 #include "ggml.h"
6 #include "gguf.h"
7
8 #include <assert.h>
9 #include <math.h>
10 #include <stdlib.h> // load `stdlib.h` before other headers to work around MinGW bug: https://sourceforge.net/p/mingw-w64/bugs/192/
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <string.h>
14
15 #ifdef __ARM_FEATURE_SVE
16 #include <arm_sve.h>
17 #endif // __ARM_FEATURE_SVE
18
19 #if defined(__ARM_NEON) && !defined(__CUDACC__) && !defined(__MUSACC__)
20 // if YCM cannot find <arm_neon.h>, make a symbolic link to it, for example:
21 //
22 // $ ln -sfn /Library/Developer/CommandLineTools/usr/lib/clang/13.1.6/include/arm_neon.h ./src/
23 //
24 #include <arm_neon.h>
25 #endif
26
27 #ifdef __cplusplus
28 extern "C" {
29 #endif
30
31 void ggml_print_backtrace(void);
32
33 #ifndef MIN
34 # define MIN(a, b) ((a) < (b) ? (a) : (b))
35 #endif
36
37 #ifndef MAX
38 # define MAX(a, b) ((a) > (b) ? (a) : (b))
39 #endif
40
41 // required for mmap as gguf only guarantees 32-byte alignment
42 #define TENSOR_ALIGNMENT 32
43
44 // static_assert should be a #define, but if it's not,
45 // fall back to the _Static_assert C11 keyword.
46 // if C99 - static_assert is noop
47 // ref: https://stackoverflow.com/a/53923785/4039976
48 #ifndef __cplusplus
49 #ifndef static_assert
50 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201100L)
51 #define static_assert(cond, msg) _Static_assert(cond, msg)
52 #else
53 #define static_assert(cond, msg) struct global_scope_noop_trick
54 #endif
55 #endif
56 #endif
57
58 static inline int ggml_up32(int n) {
59 return (n + 31) & ~31;
60 }
61
62 //static inline int ggml_up64(int n) {
63 // return (n + 63) & ~63;
64 //}
65
66 static inline int ggml_up(int n, int m) {
67 // assert m is a power of 2
68 GGML_ASSERT((m & (m - 1)) == 0);
69 return (n + m - 1) & ~(m - 1);
70 }
71
72 // TODO: move to ggml.h? (won't be able to inline)
73 static bool ggml_are_same_layout(const struct ggml_tensor * a, const struct ggml_tensor * b) {
74 if (a->type != b->type) {
75 return false;
76 }
77 for (int i = 0; i < GGML_MAX_DIMS; i++) {
78 if (a->ne[i] != b->ne[i]) {
79 return false;
80 }
81 if (a->nb[i] != b->nb[i]) {
82 return false;
83 }
84 }
85 return true;
86 }
87
88 static bool ggml_op_is_empty(enum ggml_op op) {
89 switch (op) {
90 case GGML_OP_NONE:
91 case GGML_OP_RESHAPE:
92 case GGML_OP_TRANSPOSE:
93 case GGML_OP_VIEW:
94 case GGML_OP_PERMUTE:
95 return true;
96 default:
97 return false;
98 }
99 }
100
101 static inline bool ggml_impl_is_view(const struct ggml_tensor * t) {
102 return t->view_src != NULL;
103 }
104
105 static inline float ggml_compute_softplus_f32(float input) {
106 return (input > 20.0f) ? input : logf(1 + expf(input));
107 }
108 //
109 // logging
110 //
111
112 GGML_ATTRIBUTE_FORMAT(2, 3)
113 GGML_API void ggml_log_internal (enum ggml_log_level level, const char * format, ...);
114 GGML_API void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data);
115
116 #define GGML_LOG(...) ggml_log_internal(GGML_LOG_LEVEL_NONE , __VA_ARGS__)
117 #define GGML_LOG_INFO(...) ggml_log_internal(GGML_LOG_LEVEL_INFO , __VA_ARGS__)
118 #define GGML_LOG_WARN(...) ggml_log_internal(GGML_LOG_LEVEL_WARN , __VA_ARGS__)
119 #define GGML_LOG_ERROR(...) ggml_log_internal(GGML_LOG_LEVEL_ERROR, __VA_ARGS__)
120 #define GGML_LOG_DEBUG(...) ggml_log_internal(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__)
121 #define GGML_LOG_CONT(...) ggml_log_internal(GGML_LOG_LEVEL_CONT , __VA_ARGS__)
122
123 #define GGML_DEBUG 0
124
125 #if (GGML_DEBUG >= 1)
126 #define GGML_PRINT_DEBUG(...) GGML_LOG_DEBUG(__VA_ARGS__)
127 #else
128 #define GGML_PRINT_DEBUG(...)
129 #endif
130
131 #if (GGML_DEBUG >= 5)
132 #define GGML_PRINT_DEBUG_5(...) GGML_LOG_DEBUG(__VA_ARGS__)
133 #else
134 #define GGML_PRINT_DEBUG_5(...)
135 #endif
136
137 #if (GGML_DEBUG >= 10)
138 #define GGML_PRINT_DEBUG_10(...) GGML_LOG_DEBUG(__VA_ARGS__)
139 #else
140 #define GGML_PRINT_DEBUG_10(...)
141 #endif
142
143 // tensor params
144
145 static void ggml_set_op_params(struct ggml_tensor * tensor, const void * params, size_t params_size) {
146 GGML_ASSERT(tensor != NULL); // silence -Warray-bounds warnings
147 assert(params_size <= GGML_MAX_OP_PARAMS);
148 memcpy(tensor->op_params, params, params_size);
149 }
150
151 static int32_t ggml_get_op_params_i32(const struct ggml_tensor * tensor, uint32_t i) {
152 assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
153 return ((const int32_t *)(tensor->op_params))[i];
154 }
155
156 static float ggml_get_op_params_f32(const struct ggml_tensor * tensor, uint32_t i) {
157 assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
158 return ((const float *)(tensor->op_params))[i];
159 }
160
161 static void ggml_set_op_params_i32(struct ggml_tensor * tensor, uint32_t i, int32_t value) {
162 assert(i < GGML_MAX_OP_PARAMS / sizeof(int32_t));
163 ((int32_t *)(tensor->op_params))[i] = value;
164 }
165
166 static void ggml_set_op_params_f32(struct ggml_tensor * tensor, uint32_t i, float value) {
167 assert(i < GGML_MAX_OP_PARAMS / sizeof(float));
168 ((float *)(tensor->op_params))[i] = value;
169 }
170
171 struct ggml_map_custom1_op_params {
172 ggml_custom1_op_t fun;
173 int n_tasks;
174 void * userdata;
175 };
176
177 struct ggml_map_custom2_op_params {
178 ggml_custom2_op_t fun;
179 int n_tasks;
180 void * userdata;
181 };
182
183 struct ggml_map_custom3_op_params {
184 ggml_custom3_op_t fun;
185 int n_tasks;
186 void * userdata;
187 };
188
189 struct ggml_custom_op_params {
190 ggml_custom_op_t fun;
191 int n_tasks;
192 void * userdata;
193 };
194
195 // bitset
196
197 typedef uint32_t ggml_bitset_t;
198
199 static_assert(sizeof(ggml_bitset_t) == 4, "bitset_t constants must be updated");
200 #define BITSET_SHR 5 // log2(sizeof(ggml_bitset_t)*8)
201 #define BITSET_MASK (sizeof(ggml_bitset_t)*8 - 1)
202
203 static size_t ggml_bitset_size(size_t n) {
204 return (n + BITSET_MASK) >> BITSET_SHR;
205 }
206
207 static inline bool ggml_bitset_get(const ggml_bitset_t * bitset, size_t i) {
208 return !!(bitset[i >> BITSET_SHR] & (1u << (i & BITSET_MASK)));
209 }
210
211 static inline void ggml_bitset_set(ggml_bitset_t * bitset, size_t i) {
212 bitset[i >> BITSET_SHR] |= (1u << (i & BITSET_MASK));
213 }
214
215 static inline void ggml_bitset_clear(ggml_bitset_t * bitset, size_t i) {
216 bitset[i >> BITSET_SHR] &= ~(1u << (i & BITSET_MASK));
217 }
218
219 // hash set
220
221 #define GGML_HASHSET_FULL ((size_t)-1)
222 #define GGML_HASHSET_ALREADY_EXISTS ((size_t)-2)
223
224 struct ggml_hash_set {
225 size_t size;
226 ggml_bitset_t * used; // whether or not the keys are in use i.e. set
227 struct ggml_tensor ** keys; // actual tensors in the set, keys[i] is only defined if ggml_bitset_get(used, i)
228 };
229
230 struct ggml_hash_set ggml_hash_set_new(size_t size);
231 void ggml_hash_set_free(struct ggml_hash_set * hash_set);
232
233 // returns the minimum size for a hash set that can hold min_sz elements
234 size_t ggml_hash_size(size_t min_sz);
235
236 // remove all elements from the hash set
237 void ggml_hash_set_reset(struct ggml_hash_set * hash_set);
238
239 // returns true if key is in the hash set
240 static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key);
241
242 // returns GGML_HASHSET_FULL if table is full, otherwise the current index of the key or where it should be inserted
243 static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key);
244
245 // returns GGML_HASHSET_ALREADY_EXISTS if key already exists, index otherwise, asserts if table is full
246 static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
247
248 // return index, asserts if table is full
249 static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key);
250
251 // hash function for ggml_tensor
252 static inline size_t ggml_hash(const struct ggml_tensor * p) {
253 // the last 4 bits are always zero due to alignment
254 return (size_t)(uintptr_t)p >> 4;
255 }
256
257 static size_t ggml_hash_find(const struct ggml_hash_set * hash_set, const struct ggml_tensor * key) {
258 size_t h = ggml_hash(key) % hash_set->size;
259
260 // linear probing
261 size_t i = h;
262 while (ggml_bitset_get(hash_set->used, i) && hash_set->keys[i] != key) {
263 i = (i + 1) % hash_set->size;
264 if (i == h) {
265 // visited all hash table entries -> not found
266 return GGML_HASHSET_FULL;
267 }
268 }
269 return i;
270 }
271
272 static bool ggml_hash_contains(const struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
273 size_t i = ggml_hash_find(hash_set, key);
274 return i != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, i);
275 }
276
277 static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
278 size_t h = ggml_hash(key) % hash_set->size;
279
280 // linear probing
281 size_t i = h;
282 do {
283 if (!ggml_bitset_get(hash_set->used, i)) {
284 ggml_bitset_set(hash_set->used, i);
285 hash_set->keys[i] = key;
286 return i;
287 }
288 if (hash_set->keys[i] == key) {
289 return GGML_HASHSET_ALREADY_EXISTS;
290 }
291 i = (i + 1) % hash_set->size;
292 } while (i != h);
293
294 // visited all hash table entries -> not found
295 GGML_ABORT("fatal error");
296 }
297
298 static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key) {
299 size_t h = ggml_hash(key) % hash_set->size;
300
301 // linear probing
302 size_t i = h;
303 do {
304 if (!ggml_bitset_get(hash_set->used, i)) {
305 ggml_bitset_set(hash_set->used, i);
306 hash_set->keys[i] = key;
307 return i;
308 }
309 if (hash_set->keys[i] == key) {
310 return i;
311 }
312 i = (i + 1) % hash_set->size;
313 } while (i != h);
314
315 // visited all hash table entries -> not found
316 GGML_ABORT("fatal error");
317 }
318
319 // computation graph
320
321 enum ggml_cgraph_eval_order {
322 GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT = 0,
323 GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT,
324 GGML_CGRAPH_EVAL_ORDER_COUNT
325 };
326
327 struct ggml_cgraph {
328 int size; // maximum number of nodes/leafs/grads/grad_accs
329 int n_nodes; // number of nodes currently in use
330 int n_leafs; // number of leafs currently in use
331
332 struct ggml_tensor ** nodes; // tensors with data that can change if the graph is evaluated
333 struct ggml_tensor ** grads; // the outputs of these tensors are the gradients of the nodes
334 struct ggml_tensor ** grad_accs; // accumulators for node gradients
335 struct ggml_tensor ** leafs; // tensors with constant data
336 int32_t * use_counts;// number of uses of each tensor, indexed by hash table slot
337
338 struct ggml_hash_set visited_hash_set;
339
340 enum ggml_cgraph_eval_order order;
341 };
342
343 // returns a slice of cgraph with nodes [i0, i1)
344 // the slice does not have leafs or gradients
345 // if you need the gradients, get them from the original graph
346 struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph, int i0, int i1);
347
348 // ggml-alloc.c: true if the operation can reuse memory from its sources
349 GGML_API bool ggml_op_can_inplace(enum ggml_op op);
350
351
352 // Memory allocation
353
354 GGML_API void * ggml_aligned_malloc(size_t size);
355 #ifdef __cplusplus
356 GGML_API void ggml_aligned_free(void * ptr, size_t size, bool toRemoveFromPool = true);
357 #else
358 GGML_API void ggml_aligned_free(void * ptr, size_t size, bool toRemoveFromPool);
359 #endif
360
361
362 // FP16 <-> FP32
363 // ref: https://github.com/Maratyszcza/FP16
364
365 static inline float fp32_from_bits(uint32_t w) {
366 union {
367 uint32_t as_bits;
368 float as_value;
369 } fp32;
370 fp32.as_bits = w;
371 return fp32.as_value;
372 }
373
374 static inline uint32_t fp32_to_bits(float f) {
375 union {
376 float as_value;
377 uint32_t as_bits;
378 } fp32;
379 fp32.as_value = f;
380 return fp32.as_bits;
381 }
382
383 static inline float ggml_compute_fp16_to_fp32(ggml_fp16_t h) {
384 const uint32_t w = (uint32_t) h << 16;
385 const uint32_t sign = w & UINT32_C(0x80000000);
386 const uint32_t two_w = w + w;
387
388 const uint32_t exp_offset = UINT32_C(0xE0) << 23;
389 #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
390 const float exp_scale = 0x1.0p-112f;
391 #else
392 const float exp_scale = fp32_from_bits(UINT32_C(0x7800000));
393 #endif
394 const float normalized_value = fp32_from_bits((two_w >> 4) + exp_offset) * exp_scale;
395
396 const uint32_t magic_mask = UINT32_C(126) << 23;
397 const float magic_bias = 0.5f;
398 const float denormalized_value = fp32_from_bits((two_w >> 17) | magic_mask) - magic_bias;
399
400 const uint32_t denormalized_cutoff = UINT32_C(1) << 27;
401 const uint32_t result = sign |
402 (two_w < denormalized_cutoff ? fp32_to_bits(denormalized_value) : fp32_to_bits(normalized_value));
403 return fp32_from_bits(result);
404 }
405
406 static inline ggml_fp16_t ggml_compute_fp32_to_fp16(float f) {
407 #if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) || defined(__GNUC__) && !defined(__STRICT_ANSI__)) && (!defined(__cplusplus) || __cplusplus >= 201703L)
408 const float scale_to_inf = 0x1.0p+112f;
409 const float scale_to_zero = 0x1.0p-110f;
410 #else
411 const float scale_to_inf = fp32_from_bits(UINT32_C(0x77800000));
412 const float scale_to_zero = fp32_from_bits(UINT32_C(0x08800000));
413 #endif
414 float base = (fabsf(f) * scale_to_inf) * scale_to_zero;
415
416 const uint32_t w = fp32_to_bits(f);
417 const uint32_t shl1_w = w + w;
418 const uint32_t sign = w & UINT32_C(0x80000000);
419 uint32_t bias = shl1_w & UINT32_C(0xFF000000);
420 if (bias < UINT32_C(0x71000000)) {
421 bias = UINT32_C(0x71000000);
422 }
423
424 base = fp32_from_bits((bias >> 1) + UINT32_C(0x07800000)) + base;
425 const uint32_t bits = fp32_to_bits(base);
426 const uint32_t exp_bits = (bits >> 13) & UINT32_C(0x00007C00);
427 const uint32_t mantissa_bits = bits & UINT32_C(0x00000FFF);
428 const uint32_t nonsign = exp_bits + mantissa_bits;
429 return (sign >> 16) | (shl1_w > UINT32_C(0xFF000000) ? UINT16_C(0x7E00) : nonsign);
430 }
431
432 #define GGML_COMPUTE_FP16_TO_FP32(x) ggml_compute_fp16_to_fp32(x)
433 #define GGML_COMPUTE_FP32_TO_FP16(x) ggml_compute_fp32_to_fp16(x)
434
435 #define GGML_FP16_TO_FP32(x) GGML_COMPUTE_FP16_TO_FP32(x)
436 #define GGML_FP32_TO_FP16(x) GGML_COMPUTE_FP32_TO_FP16(x)
437
438 static inline float ggml_e8m0_to_fp32(uint8_t x) {
439 uint32_t bits; // Stores the raw bit representation of the float
440
441 // Handle special case for minimum exponent (denormalized float)
442 if (x == 0) {
443 // Bit pattern for 2^(-127):
444 // - Sign bit: 0 (positive)
445 // - Exponent: 0 (denormalized number)
446 // - Mantissa: 0x400000 (0.5 in fractional form)
447 // Value = 0.5 * 2^(-126) = 2^(-127)
448 bits = 0x00400000;
449 }
450 // note: disabled as we don't need to handle NaNs
451 //// Handle special case for NaN (all bits set)
452 //else if (x == 0xFF) {
453 // // Standard quiet NaN pattern:
454 // // - Sign bit: 0
455 // // - Exponent: all 1s (0xFF)
456 // // - Mantissa: 0x400000 (quiet NaN flag)
457 // bits = 0x7FC00000;
458 //}
459 // Normalized values (most common case)
460 else {
461 // Construct normalized float by shifting exponent into position:
462 // - Exponent field: 8 bits (positions 30-23)
463 // - Mantissa: 0 (implicit leading 1)
464 // Value = 2^(x - 127)
465 bits = (uint32_t) x << 23;
466 }
467
468 float result; // Final float value
469 // Safely reinterpret bit pattern as float without type-punning issues
470 memcpy(&result, &bits, sizeof(float));
471 return result;
472 }
473
474 // Equal to ggml_e8m0_to_fp32/2
475 // Useful with MXFP4 quantization since the E0M2 values are doubled
476 static inline float ggml_e8m0_to_fp32_half(uint8_t x) {
477 uint32_t bits;
478
479 // For x < 2: use precomputed denormal patterns
480 if (x < 2) {
481 // 0x00200000 = 2^(-128), 0x00400000 = 2^(-127)
482 bits = 0x00200000 << x;
483 }
484 // For x >= 2: normalized exponent adjustment
485 else {
486 // 0.5 * 2^(x-127) = 2^(x-128) = normalized with exponent (x-1)
487 bits = (uint32_t)(x - 1) << 23;
488 }
489 // Note: NaNs are not handled here
490
491 float result;
492 memcpy(&result, &bits, sizeof(float));
493 return result;
494 }
495
496 #define GGML_E8M0_TO_FP32(x) ggml_e8m0_to_fp32(x)
497 #define GGML_E8M0_TO_FP32_HALF(x) ggml_e8m0_to_fp32_half(x)
498
499 /**
500 * Converts brain16 to float32.
501 *
502 * The bfloat16 floating point format has the following structure:
503 *
504 * ┌sign
505 * │
506 * │ ┌exponent
507 * │ │
508 * │ │ ┌mantissa
509 * │ │ │
510 * │┌──┴───┐┌─┴───┐
511 * 0b0000000000000000 brain16
512 *
513 * Since bf16 has the same number of exponent bits as a 32bit float,
514 * encoding and decoding numbers becomes relatively straightforward.
515 *
516 * ┌sign
517 * │
518 * │ ┌exponent
519 * │ │
520 * │ │ ┌mantissa
521 * │ │ │
522 * │┌──┴───┐┌─┴───────────────────┐
523 * 0b00000000000000000000000000000000 IEEE binary32
524 *
525 * For comparison, the standard fp16 format has fewer exponent bits.
526 *
527 * ┌sign
528 * │
529 * │ ┌exponent
530 * │ │
531 * │ │ ┌mantissa
532 * │ │ │
533 * │┌─┴─┐┌─┴──────┐
534 * 0b0000000000000000 IEEE binary16
535 *
536 * @see IEEE 754-2008
537 */
538 static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) {
539 union {
540 float f;
541 uint32_t i;
542 } u;
543 u.i = (uint32_t)h.bits << 16;
544 return u.f;
545 }
546
547 /**
548 * Converts float32 to brain16.
549 *
550 * This is binary identical with Google Brain float conversion.
551 * Floats shall round to nearest even, and NANs shall be quiet.
552 * Subnormals aren't flushed to zero, except perhaps when used.
553 * This code should vectorize nicely if using modern compilers.
554 */
555 static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) {
556 ggml_bf16_t h;
557 union {
558 float f;
559 uint32_t i;
560 } u;
561 u.f = s;
562 if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */
563 h.bits = (u.i >> 16) | 64; /* force to quiet */
564 return h;
565 }
566 h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16;
567 return h;
568 }
569
570 #define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x)
571 #define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x)
572
573 static inline int32_t ggml_node_get_use_count(const struct ggml_cgraph * cgraph, int node_idx) {
574 const struct ggml_tensor * node = cgraph->nodes[node_idx];
575
576 size_t hash_pos = ggml_hash_find(&cgraph->visited_hash_set, node);
577 if (!ggml_bitset_get(cgraph->visited_hash_set.used, hash_pos)) {
578 return 0;
579 }
580 return cgraph->use_counts[hash_pos];
581 }
582
583 // return true if the node's results are only used by N other nodes
584 // and can be fused into their calculations.
585 static inline bool ggml_node_has_n_uses(const struct ggml_cgraph * cgraph, int node_idx, int32_t n_uses) {
586 const struct ggml_tensor * node = cgraph->nodes[node_idx];
587
588 // check the use count against how many we're replacing
589 if (ggml_node_get_use_count(cgraph, node_idx) != n_uses) {
590 return false;
591 }
592
593 // if node is a view, some other node might be using the intermediate result
594 // via the view source.
595 if (node->view_src) {
596 return false;
597 }
598
599 // If the user requested output for the node, can't fuse
600 if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
601 return false;
602 }
603
604 return true;
605 }
606
607 // Returns true if nodes with indices { node_idxs } are the sequence of ggml_ops in ops[]
608 // and are fusable. Nodes are considered fusable according to this function if:
609 // - all nodes except the last have only one use and are not views/outputs (see ggml_node_has_N_uses).
610 // - all nodes except the last are a src of the following node.
611 // - all nodes are the same shape.
612 // TODO: Consider allowing GGML_OP_NONE nodes in between
613 static inline bool ggml_can_fuse_ext(const struct ggml_cgraph * cgraph, const int * node_idxs, const enum ggml_op * ops, int num_ops) {
614 for (int i = 0; i < num_ops; ++i) {
615 if (node_idxs[i] >= cgraph->n_nodes) {
616 return false;
617 }
618
619 struct ggml_tensor * node = cgraph->nodes[node_idxs[i]];
620 if (node->op != ops[i]) {
621 return false;
622 }
623 if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
624 return false;
625 }
626 if (i < num_ops - 1 && !ggml_node_has_n_uses(cgraph, node_idxs[i], 1)) {
627 return false;
628 }
629 if (i > 0) {
630 struct ggml_tensor * prev = cgraph->nodes[node_idxs[i - 1]];
631 if (node->src[0] != prev && node->src[1] != prev) {
632 return false;
633 }
634 if (!ggml_are_same_shape(node, prev)) {
635 return false;
636 }
637 }
638 }
639 return true;
640 }
641
642 // same as above, for sequential indices starting at node_idx
643 static inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, const enum ggml_op * ops, int num_ops) {
644 assert(num_ops < 32);
645
646 if (node_idx + num_ops > cgraph->n_nodes) {
647 return false;
648 }
649
650 int idxs[32];
651 for (int i = 0; i < num_ops; ++i) {
652 idxs[i] = node_idx + i;
653 }
654
655 return ggml_can_fuse_ext(cgraph, idxs, ops, num_ops);
656 }
657
658 GGML_API bool ggml_can_fuse_subgraph_ext(const struct ggml_cgraph * cgraph,
659 const int * node_idxs,
660 int count,
661 const enum ggml_op * ops,
662 const int * outputs,
663 int num_outputs);
664
665 // Returns true if the subgraph formed by {node_idxs} can be fused
666 // checks whethers all nodes which are not part of outputs can be elided
667 // by checking if their num_uses are confined to the subgraph
668 static inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph,
669 int node_idx,
670 int count,
671 const enum ggml_op * ops,
672 const int * outputs,
673 int num_outputs) {
674 GGML_ASSERT(count < 32);
675 if (node_idx + count > cgraph->n_nodes) {
676 return false;
677 }
678
679 int idxs[32];
680
681 for (int i = 0; i < count; ++i) {
682 idxs[i] = node_idx + i;
683 }
684
685 return ggml_can_fuse_subgraph_ext(cgraph, idxs, count, ops, outputs, num_outputs);
686 }
687
688 #ifdef __cplusplus
689 }
690 #endif
691
692 #ifdef __cplusplus
693 #include <array>
694 #include <initializer_list>
695 #include <vector>
696
697 // nicer C++ syntax for ggml_can_fuse
698 inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) {
699 return ggml_can_fuse(cgraph, node_idx, ops.begin(), (int)ops.size());
700 }
701
702 inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph,
703 int start_idx,
704 std::initializer_list<enum ggml_op> ops,
705 std::initializer_list<int> outputs = {}) {
706 return ggml_can_fuse_subgraph(cgraph, start_idx, ops.size(), ops.begin(), outputs.begin(), outputs.size());
707 }
708
709 // Return true if the edges in the graph match expectations.
710 inline bool ggml_check_edges(const struct ggml_cgraph * cgraph,
711 int start_idx,
712 std::initializer_list<std::array<int, 3>> edges) {
713 for (const auto & edge : edges) {
714 int dst_node = edge[0];
715 int src_idx = edge[1];
716 int src_node = edge[2];
717 if (cgraph->nodes[start_idx + dst_node]->src[src_idx] != cgraph->nodes[start_idx + src_node]) {
718 return false;
719 }
720 }
721 return true;
722 }
723
724 // expose GGUF internals for test code
725 GGML_API size_t gguf_type_size(enum gguf_type type);
726 GGML_API struct gguf_context * gguf_init_from_file_impl(FILE * file, struct gguf_init_params params);
727 GGML_API void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta);
728 #endif // __cplusplus