ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
| 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 | uint64_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 | |
| 60 | static 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 | |
| 68 | static 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) |
| 75 | static 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 | |
| 90 | static 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 | |
| 103 | static inline bool ggml_impl_is_view(const struct ggml_tensor * t) { |
| 104 | return t->view_src != NULL; |
| 105 | } |
| 106 | |
| 107 | static inline float ggml_compute_softplus_f32(float input) { |
| 108 | return (input > 20.0f) ? input : logf(1 + expf(input)); |
| 109 | } |
| 110 | // |
| 111 | // logging |
| 112 | // |
| 113 | |
| 114 | GGML_ATTRIBUTE_FORMAT(2, 3) |
| 115 | GGML_API void ggml_log_internal (enum ggml_log_level level, const char * format, ...); |
| 116 | GGML_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 | |
| 147 | static 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 | |
| 153 | static 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 | |
| 158 | static 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 |
| 175 | static 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 | |
| 180 | static 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 | |
| 185 | struct ggml_map_custom1_op_params { |
| 186 | ggml_custom1_op_t fun; |
| 187 | int n_tasks; |
| 188 | void * userdata; |
| 189 | }; |
| 190 | |
| 191 | struct ggml_map_custom2_op_params { |
| 192 | ggml_custom2_op_t fun; |
| 193 | int n_tasks; |
| 194 | void * userdata; |
| 195 | }; |
| 196 | |
| 197 | struct ggml_map_custom3_op_params { |
| 198 | ggml_custom3_op_t fun; |
| 199 | int n_tasks; |
| 200 | void * userdata; |
| 201 | }; |
| 202 | |
| 203 | struct ggml_custom_op_params { |
| 204 | ggml_custom_op_t fun; |
| 205 | int n_tasks; |
| 206 | void * userdata; |
| 207 | }; |
| 208 | |
| 209 | // bitset |
| 210 | |
| 211 | typedef uint32_t ggml_bitset_t; |
| 212 | |
| 213 | static_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 | |
| 217 | static size_t ggml_bitset_size(size_t n) { |
| 218 | return (n + BITSET_MASK) >> BITSET_SHR; |
| 219 | } |
| 220 | |
| 221 | static 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 | |
| 225 | static inline void ggml_bitset_set(ggml_bitset_t * bitset, size_t i) { |
| 226 | bitset[i >> BITSET_SHR] |= (1u << (i & BITSET_MASK)); |
| 227 | } |
| 228 | |
| 229 | static 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 | |
| 238 | struct 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 | |
| 244 | struct ggml_hash_set ggml_hash_set_new(size_t size); |
| 245 | void 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 |
| 248 | size_t ggml_hash_size(size_t min_sz); |
| 249 | |
| 250 | // remove all elements from the hash set |
| 251 | void ggml_hash_set_reset(struct ggml_hash_set * hash_set); |
| 252 | |
| 253 | // returns true if key is in the hash set |
| 254 | static 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 |
| 257 | static 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 |
| 260 | static size_t ggml_hash_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key); |
| 261 | |
| 262 | // return index, asserts if table is full |
| 263 | static size_t ggml_hash_find_or_insert(struct ggml_hash_set * hash_set, struct ggml_tensor * key); |
| 264 | |
| 265 | // hash function for ggml_tensor |
| 266 | static 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 | |
| 271 | static 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 | |
| 286 | static 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 | |
| 291 | static 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 | |
| 312 | static 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 | |
| 335 | enum 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 | |
| 341 | struct 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 |
| 364 | struct 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 |
| 367 | GGML_API bool ggml_op_can_inplace(enum ggml_op op); |
| 368 | |
| 369 | |
| 370 | // Memory allocation |
| 371 | |
| 372 | GGML_API void * ggml_aligned_malloc(size_t size); |
| 373 | GGML_API void ggml_aligned_free(void * ptr, size_t size); |
| 374 | |
| 375 | // FP16 <-> FP32 |
| 376 | // ref: https://github.com/Maratyszcza/FP16 |
| 377 | |
| 378 | static 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 | |
| 387 | static 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 | |
| 396 | static 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 | |
| 419 | static 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 | |
| 451 | static 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 |
| 489 | static 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) |
| 514 | static inline float ggml_ue4m3_to_fp32(uint8_t x) { |
| 515 | // TODO: reject invalid unsigned E4M3 scales instead of decoding NaN as zero or ignoring the sign bit. |
| 516 | if (x == 0 || x == 0x7F) { |
| 517 | return 0.0f; |
| 518 | } |
| 519 | int exp = (x >> 3) & 0xF; |
| 520 | int man = x & 0x7; |
| 521 | float raw; |
| 522 | if (exp == 0) { |
| 523 | raw = ldexpf((float) man, -9); |
| 524 | } else { |
| 525 | raw = ldexpf(1.0f + (float) man / 8.0f, exp - 7); |
| 526 | } |
| 527 | return raw * 0.5f; |
| 528 | } |
| 529 | |
| 530 | static inline uint8_t ggml_fp32_to_ue4m3(float x) { |
| 531 | // TODO: use ties-to-even rounding, allow subnormal carry, and preserve finite values with exponent field 15. |
| 532 | if (!(x > 0.0f)) { |
| 533 | return 0; |
| 534 | } |
| 535 | if (x > 448.0f) { |
| 536 | x = 448.0f; |
| 537 | } |
| 538 | uint32_t bits; |
| 539 | memcpy(&bits, &x, 4); |
| 540 | int fp32_exp = ((bits >> 23) & 0xFF) - 127; |
| 541 | int fp32_man = (bits >> 20) & 0x7; |
| 542 | int ue4m3_exp = fp32_exp + 7; |
| 543 | if (ue4m3_exp <= 0) { |
| 544 | // subnormal: value = man * 2^-9, man = round(x * 2^9) |
| 545 | int man = (int) (x * 512.0f + 0.5f); |
| 546 | if (man > 7) { |
| 547 | man = 7; |
| 548 | } |
| 549 | if (man < 1) { |
| 550 | return 0; |
| 551 | } |
| 552 | return (uint8_t) man; |
| 553 | } |
| 554 | if (ue4m3_exp >= 15) { |
| 555 | return 0x7E; |
| 556 | } |
| 557 | int round_bit = (bits >> 19) & 1; |
| 558 | int ue4m3_man = fp32_man + round_bit; |
| 559 | if (ue4m3_man > 7) { |
| 560 | ue4m3_man = 0; |
| 561 | ue4m3_exp++; |
| 562 | if (ue4m3_exp >= 15) { |
| 563 | return 0x7E; |
| 564 | } |
| 565 | } |
| 566 | return (uint8_t) ((ue4m3_exp << 3) | ue4m3_man); |
| 567 | } |
| 568 | |
| 569 | static inline float ggml_f8_e4m3_to_fp32(uint8_t x) { |
| 570 | const uint8_t ax = x & 0x7F; |
| 571 | if (ax == 0x7F) { |
| 572 | // OCP FP8 defines both 0x7F and 0xFF as NaN; the sign need not be preserved. |
| 573 | return NAN; |
| 574 | } |
| 575 | |
| 576 | const int exp = (ax >> 3) & 0xF; |
| 577 | const int man = ax & 0x7; |
| 578 | // OCP FP8 rev. 1.1, section 5.1: subnormal magnitude = M * 2^-9; normal magnitude = (1 + M / 8) * 2^(E - 7). |
| 579 | const float value = exp == 0 |
| 580 | ? ldexpf((float) man, -9) |
| 581 | : ldexpf(1.0f + (float) man / 8.0f, exp - 7); |
| 582 | return x & 0x80 ? -value : value; |
| 583 | } |
| 584 | |
| 585 | static inline int ggml_round_to_nearest_even(float x) { |
| 586 | const int value = (int) floorf(x); |
| 587 | const float fraction = x - value; |
| 588 | return fraction > 0.5f || (fraction == 0.5f && (value & 1)) ? value + 1 : value; |
| 589 | } |
| 590 | |
| 591 | // Supports saturating conversion only; infinities and overflow clamp to +/-448. |
| 592 | static inline uint8_t ggml_fp32_to_f8_e4m3(float x) { |
| 593 | const uint8_t sign = signbit(x) ? 0x80 : 0; |
| 594 | x = fabsf(x); |
| 595 | |
| 596 | if (isnan(x)) { |
| 597 | // OCP FP8 leaves NaN sign handling to the implementation; use canonical 0x7F. |
| 598 | return 0x7F; |
| 599 | } |
| 600 | if (x == 0.0f) { |
| 601 | return sign; |
| 602 | } |
| 603 | if (isinf(x) || x >= 448.0f) { |
| 604 | return sign | 0x7E; |
| 605 | } |
| 606 | if (x < 0.015625f) { |
| 607 | // OCP FP8 rev. 1.1, section 5.1: subnormal magnitude = M * 2^(1 - bias - m) = M / 512. |
| 608 | return sign | (uint8_t) ggml_round_to_nearest_even(x * 512.0f); |
| 609 | } |
| 610 | |
| 611 | int exp; |
| 612 | const float mantissa = frexpf(x, &exp) * 2.0f; |
| 613 | int encoded_exp = exp + 6; |
| 614 | int encoded_man = ggml_round_to_nearest_even((mantissa - 1.0f) * 8.0f); |
| 615 | if (encoded_man == 8) { |
| 616 | encoded_man = 0; |
| 617 | encoded_exp++; |
| 618 | } |
| 619 | if (encoded_exp > 15 || (encoded_exp == 15 && encoded_man > 6)) { |
| 620 | return sign | 0x7E; |
| 621 | } |
| 622 | return sign | (uint8_t) (encoded_exp << 3) | (uint8_t) encoded_man; |
| 623 | } |
| 624 | |
| 625 | /** |
| 626 | * Converts brain16 to float32. |
| 627 | * |
| 628 | * The bfloat16 floating point format has the following structure: |
| 629 | * |
| 630 | * ┌sign |
| 631 | * │ |
| 632 | * │ ┌exponent |
| 633 | * │ │ |
| 634 | * │ │ ┌mantissa |
| 635 | * │ │ │ |
| 636 | * │┌──┴───┐┌─┴───┐ |
| 637 | * 0b0000000000000000 brain16 |
| 638 | * |
| 639 | * Since bf16 has the same number of exponent bits as a 32bit float, |
| 640 | * encoding and decoding numbers becomes relatively straightforward. |
| 641 | * |
| 642 | * ┌sign |
| 643 | * │ |
| 644 | * │ ┌exponent |
| 645 | * │ │ |
| 646 | * │ │ ┌mantissa |
| 647 | * │ │ │ |
| 648 | * │┌──┴───┐┌─┴───────────────────┐ |
| 649 | * 0b00000000000000000000000000000000 IEEE binary32 |
| 650 | * |
| 651 | * For comparison, the standard fp16 format has fewer exponent bits. |
| 652 | * |
| 653 | * ┌sign |
| 654 | * │ |
| 655 | * │ ┌exponent |
| 656 | * │ │ |
| 657 | * │ │ ┌mantissa |
| 658 | * │ │ │ |
| 659 | * │┌─┴─┐┌─┴──────┐ |
| 660 | * 0b0000000000000000 IEEE binary16 |
| 661 | * |
| 662 | * @see IEEE 754-2008 |
| 663 | */ |
| 664 | static inline float ggml_compute_bf16_to_fp32(ggml_bf16_t h) { |
| 665 | union { |
| 666 | float f; |
| 667 | uint32_t i; |
| 668 | } u; |
| 669 | u.i = (uint32_t)h.bits << 16; |
| 670 | return u.f; |
| 671 | } |
| 672 | |
| 673 | /** |
| 674 | * Converts float32 to brain16. |
| 675 | * |
| 676 | * This is binary identical with Google Brain float conversion. |
| 677 | * Floats shall round to nearest even, and NANs shall be quiet. |
| 678 | * Subnormals aren't flushed to zero, except perhaps when used. |
| 679 | * This code should vectorize nicely if using modern compilers. |
| 680 | */ |
| 681 | static inline ggml_bf16_t ggml_compute_fp32_to_bf16(float s) { |
| 682 | ggml_bf16_t h; |
| 683 | union { |
| 684 | float f; |
| 685 | uint32_t i; |
| 686 | } u; |
| 687 | u.f = s; |
| 688 | if ((u.i & 0x7fffffff) > 0x7f800000) { /* nan */ |
| 689 | h.bits = (u.i >> 16) | 64; /* force to quiet */ |
| 690 | return h; |
| 691 | } |
| 692 | h.bits = (u.i + (0x7fff + ((u.i >> 16) & 1))) >> 16; |
| 693 | return h; |
| 694 | } |
| 695 | |
| 696 | #define GGML_FP32_TO_BF16(x) ggml_compute_fp32_to_bf16(x) |
| 697 | #define GGML_BF16_TO_FP32(x) ggml_compute_bf16_to_fp32(x) |
| 698 | |
| 699 | static inline int32_t ggml_node_get_use_count(const struct ggml_cgraph * cgraph, int node_idx) { |
| 700 | const struct ggml_tensor * node = cgraph->nodes[node_idx]; |
| 701 | |
| 702 | size_t hash_pos = ggml_hash_find(&cgraph->visited_hash_set, node); |
| 703 | if (!ggml_bitset_get(cgraph->visited_hash_set.used, hash_pos)) { |
| 704 | return 0; |
| 705 | } |
| 706 | return cgraph->use_counts[hash_pos]; |
| 707 | } |
| 708 | |
| 709 | // return true if the node's results are only used by N other nodes |
| 710 | // and can be fused into their calculations. |
| 711 | static inline bool ggml_node_has_n_uses(const struct ggml_cgraph * cgraph, int node_idx, int32_t n_uses) { |
| 712 | const struct ggml_tensor * node = cgraph->nodes[node_idx]; |
| 713 | |
| 714 | // check the use count against how many we're replacing |
| 715 | if (ggml_node_get_use_count(cgraph, node_idx) != n_uses) { |
| 716 | return false; |
| 717 | } |
| 718 | |
| 719 | // if node is a view, some other node might be using the intermediate result |
| 720 | // via the view source. |
| 721 | if (node->view_src) { |
| 722 | return false; |
| 723 | } |
| 724 | |
| 725 | // If the user requested output for the node, can't fuse |
| 726 | if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { |
| 727 | return false; |
| 728 | } |
| 729 | |
| 730 | return true; |
| 731 | } |
| 732 | |
| 733 | // Returns true if nodes with indices { node_idxs } are the sequence of ggml_ops in ops[] |
| 734 | // and are fusable. Nodes are considered fusable according to this function if: |
| 735 | // - all nodes except the last have only one use and are not views/outputs (see ggml_node_has_N_uses). |
| 736 | // - all nodes except the last are a src of the following node. |
| 737 | // - all nodes are the same shape. |
| 738 | // TODO: Consider allowing GGML_OP_NONE nodes in between |
| 739 | static inline bool ggml_can_fuse_ext(const struct ggml_cgraph * cgraph, const int * node_idxs, const enum ggml_op * ops, int num_ops) { |
| 740 | for (int i = 0; i < num_ops; ++i) { |
| 741 | if (node_idxs[i] >= cgraph->n_nodes) { |
| 742 | return false; |
| 743 | } |
| 744 | |
| 745 | struct ggml_tensor * node = cgraph->nodes[node_idxs[i]]; |
| 746 | if (node->op != ops[i]) { |
| 747 | return false; |
| 748 | } |
| 749 | if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { |
| 750 | return false; |
| 751 | } |
| 752 | if (i < num_ops - 1 && !ggml_node_has_n_uses(cgraph, node_idxs[i], 1)) { |
| 753 | return false; |
| 754 | } |
| 755 | if (i > 0) { |
| 756 | struct ggml_tensor * prev = cgraph->nodes[node_idxs[i - 1]]; |
| 757 | if (node->src[0] != prev && node->src[1] != prev) { |
| 758 | return false; |
| 759 | } |
| 760 | if (!ggml_are_same_shape(node, prev)) { |
| 761 | return false; |
| 762 | } |
| 763 | } |
| 764 | } |
| 765 | return true; |
| 766 | } |
| 767 | |
| 768 | // same as above, for sequential indices starting at node_idx |
| 769 | static inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, const enum ggml_op * ops, int num_ops) { |
| 770 | assert(num_ops < 32); |
| 771 | |
| 772 | if (node_idx + num_ops > cgraph->n_nodes) { |
| 773 | return false; |
| 774 | } |
| 775 | |
| 776 | int idxs[32]; |
| 777 | for (int i = 0; i < num_ops; ++i) { |
| 778 | idxs[i] = node_idx + i; |
| 779 | } |
| 780 | |
| 781 | return ggml_can_fuse_ext(cgraph, idxs, ops, num_ops); |
| 782 | } |
| 783 | |
| 784 | GGML_API bool ggml_can_fuse_subgraph_ext(const struct ggml_cgraph * cgraph, |
| 785 | const int * node_idxs, |
| 786 | int count, |
| 787 | const enum ggml_op * ops, |
| 788 | const int * outputs, |
| 789 | int num_outputs); |
| 790 | |
| 791 | // Returns true if the subgraph formed by {node_idxs} can be fused |
| 792 | // checks whethers all nodes which are not part of outputs can be elided |
| 793 | // by checking if their num_uses are confined to the subgraph |
| 794 | static inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph, |
| 795 | int node_idx, |
| 796 | int count, |
| 797 | const enum ggml_op * ops, |
| 798 | const int * outputs, |
| 799 | int num_outputs) { |
| 800 | GGML_ASSERT(count < 32); |
| 801 | if (node_idx + count > cgraph->n_nodes) { |
| 802 | return false; |
| 803 | } |
| 804 | |
| 805 | int idxs[32]; |
| 806 | |
| 807 | for (int i = 0; i < count; ++i) { |
| 808 | idxs[i] = node_idx + i; |
| 809 | } |
| 810 | |
| 811 | return ggml_can_fuse_subgraph_ext(cgraph, idxs, count, ops, outputs, num_outputs); |
| 812 | } |
| 813 | |
| 814 | #ifdef __cplusplus |
| 815 | } |
| 816 | #endif |
| 817 | |
| 818 | #ifdef __cplusplus |
| 819 | #include <array> |
| 820 | #include <initializer_list> |
| 821 | #include <vector> |
| 822 | |
| 823 | // nicer C++ syntax for ggml_can_fuse |
| 824 | inline bool ggml_can_fuse(const struct ggml_cgraph * cgraph, int node_idx, std::initializer_list<enum ggml_op> ops) { |
| 825 | return ggml_can_fuse(cgraph, node_idx, ops.begin(), (int)ops.size()); |
| 826 | } |
| 827 | |
| 828 | inline bool ggml_can_fuse_subgraph(const struct ggml_cgraph * cgraph, |
| 829 | int start_idx, |
| 830 | std::initializer_list<enum ggml_op> ops, |
| 831 | std::initializer_list<int> outputs = {}) { |
| 832 | return ggml_can_fuse_subgraph(cgraph, start_idx, ops.size(), ops.begin(), outputs.begin(), outputs.size()); |
| 833 | } |
| 834 | |
| 835 | // Return true if the edges in the graph match expectations. |
| 836 | inline bool ggml_check_edges(const struct ggml_cgraph * cgraph, |
| 837 | int start_idx, |
| 838 | std::initializer_list<std::array<int, 3>> edges) { |
| 839 | for (const auto & edge : edges) { |
| 840 | int dst_node = edge[0]; |
| 841 | int src_idx = edge[1]; |
| 842 | int src_node = edge[2]; |
| 843 | if (cgraph->nodes[start_idx + dst_node]->src[src_idx] != cgraph->nodes[start_idx + src_node]) { |
| 844 | return false; |
| 845 | } |
| 846 | } |
| 847 | return true; |
| 848 | } |
| 849 | |
| 850 | // expose GGUF internals for test code |
| 851 | GGML_API size_t gguf_type_size(enum gguf_type type); |
| 852 | GGML_API void gguf_write_to_buf(const struct gguf_context * ctx, std::vector<int8_t> & buf, bool only_meta); |
| 853 | #endif // __cplusplus |