char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Georgi Gerganovggml : update ggml_prec specification (#26675)5a6caa05f

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