char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
5a6caa05f
char/aliceai-t5-moe
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 ) { 61return (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 70GGML_ASSERT ((m & (m - 1 ))== 0 ); 71return (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 ) { 76if (a -> type != b -> type ) { 77return false; 78 } 79for (int i = 0 ;i < GGML_MAX_DIMS ;i ++ ) { 80if (a -> ne [i ]!= b -> ne [i ]) { 81return false; 82 } 83if (a -> nb [i ]!= b -> nb [i ]) { 84return false; 85 } 86 } 87return true; 88} 89 90static bool ggml_op_is_empty (enum ggml_op op ) { 91switch (op ) { 92case GGML_OP_NONE : 93case GGML_OP_RESHAPE : 94case GGML_OP_TRANSPOSE : 95case GGML_OP_VIEW : 96case GGML_OP_PERMUTE : 97return true; 98default : 99return false; 100 } 101} 102 103static inline bool ggml_impl_is_view (const struct ggml_tensor * t ) { 104return t -> view_src != NULL ; 105} 106 107static inline float ggml_compute_softplus_f32 (float input ) { 108return (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 ) { 148GGML_ASSERT (tensor != NULL );// silence -Warray-bounds warnings 149assert (params_size <=GGML_MAX_OP_PARAMS ); 150memcpy (tensor -> op_params ,params ,params_size ); 151} 152 153static int32_t ggml_get_op_params_i32 (const struct ggml_tensor * tensor ,uint32_t i ) { 154assert (i < GGML_MAX_OP_PARAMS /sizeof (int32_t )); 155return ((const int32_t * )(tensor -> op_params ))[i ]; 156} 157 158static float ggml_get_op_params_f32 (const struct ggml_tensor * tensor ,uint32_t i ) { 159assert (i < GGML_MAX_OP_PARAMS /sizeof (float )); 160return ((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 ) { 176assert (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 ) { 181assert (i < GGML_MAX_OP_PARAMS /sizeof (float )); 182 ((float * )(tensor -> op_params ))[i ]= value ; 183} 184 185struct ggml_map_custom1_op_params { 186ggml_custom1_op_t fun ; 187int n_tasks ; 188void * userdata ; 189}; 190 191struct ggml_map_custom2_op_params { 192ggml_custom2_op_t fun ; 193int n_tasks ; 194void * userdata ; 195}; 196 197struct ggml_map_custom3_op_params { 198ggml_custom3_op_t fun ; 199int n_tasks ; 200void * userdata ; 201}; 202 203struct ggml_custom_op_params { 204ggml_custom_op_t fun ; 205int n_tasks ; 206void * 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 ) { 218return (n + BITSET_MASK ) >>BITSET_SHR ; 219} 220 221static inline bool ggml_bitset_get (const ggml_bitset_t * bitset ,size_t i ) { 222return !!(bitset [i >>BITSET_SHR ]& (1u << (i & BITSET_MASK ))); 223} 224 225static inline void ggml_bitset_set (ggml_bitset_t * bitset ,size_t i ) { 226bitset [i >>BITSET_SHR ] |= (1u << (i & BITSET_MASK )); 227} 228 229static inline void ggml_bitset_clear (ggml_bitset_t * bitset ,size_t i ) { 230bitset [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 { 239size_t size ; 240ggml_bitset_t * used ;// whether or not the keys are in use i.e. set 241struct 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 268return (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 ) { 272size_t h = ggml_hash (key ) %hash_set -> size ; 273 274// linear probing 275size_t i = h ; 276while (ggml_bitset_get (hash_set -> used ,i )&& hash_set -> keys [i ]!= key ) { 277i = (i + 1 ) %hash_set -> size ; 278if (i == h ) { 279// visited all hash table entries -> not found 280return GGML_HASHSET_FULL ; 281 } 282 } 283return i ; 284} 285 286static bool ggml_hash_contains (const struct ggml_hash_set * hash_set ,struct ggml_tensor * key ) { 287size_t i = ggml_hash_find (hash_set ,key ); 288return 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 ) { 292size_t h = ggml_hash (key ) %hash_set -> size ; 293 294// linear probing 295size_t i = h ; 296do { 297if (!ggml_bitset_get (hash_set -> used ,i )) { 298ggml_bitset_set (hash_set -> used ,i ); 299hash_set -> keys [i ]= key ; 300return i ; 301 } 302if (hash_set -> keys [i ]== key ) { 303return GGML_HASHSET_ALREADY_EXISTS ; 304 } 305i = (i + 1 ) %hash_set -> size ; 306 }while (i != h ); 307 308// visited all hash table entries -> not found 309GGML_ABORT ("fatal error" ); 310} 311 312static size_t ggml_hash_find_or_insert (struct ggml_hash_set * hash_set ,struct ggml_tensor * key ) { 313size_t h = ggml_hash (key ) %hash_set -> size ; 314 315// linear probing 316size_t i = h ; 317do { 318if (!ggml_bitset_get (hash_set -> used ,i )) { 319ggml_bitset_set (hash_set -> used ,i ); 320hash_set -> keys [i ]= key ; 321return i ; 322 } 323if (hash_set -> keys [i ]== key ) { 324return i ; 325 } 326i = (i + 1 ) %hash_set -> size ; 327 }while (i != h ); 328 329// visited all hash table entries -> not found 330GGML_ABORT ("fatal error" ); 331} 332 333// computation graph 334 335enum ggml_cgraph_eval_order { 336GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT = 0 , 337GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT , 338GGML_CGRAPH_EVAL_ORDER_COUNT 339}; 340 341struct ggml_cgraph { 342int size ;// maximum number of nodes/leafs/grads/grad_accs 343int n_nodes ;// number of nodes currently in use 344int n_leafs ;// number of leafs currently in use 345 346struct ggml_tensor ** nodes ;// tensors with data that can change if the graph is evaluated 347struct ggml_tensor ** grads ;// the outputs of these tensors are the gradients of the nodes 348struct ggml_tensor ** grad_accs ;// accumulators for node gradients 349struct ggml_tensor ** leafs ;// tensors with constant data 350int32_t * use_counts ;// number of uses of each tensor, indexed by hash table slot 351 352struct ggml_hash_set visited_hash_set ; 353 354enum 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 358uint64_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 ) { 379union { 380uint32_t as_bits ; 381float as_value ; 382 }fp32 ; 383fp32 .as_bits = w ; 384return fp32 .as_value ; 385} 386 387static inline uint32_t fp32_to_bits (float f ) { 388union { 389float as_value ; 390uint32_t as_bits ; 391 }fp32 ; 392fp32 .as_value = f ; 393return fp32 .as_bits ; 394} 395 396static inline float ggml_compute_fp16_to_fp32 (ggml_fp16_t h ) { 397const uint32_t w = (uint32_t )h <<16 ; 398const uint32_t sign = w & UINT32_C (0x80000000 ); 399const uint32_t two_w = w + w ; 400 401const 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 ) 403const float exp_scale = 0x1.0p-112f ; 404#else 405const float exp_scale = fp32_from_bits (UINT32_C (0x7800000 )); 406#endif 407const float normalized_value = fp32_from_bits ((two_w >>4 )+ exp_offset )* exp_scale ; 408 409const uint32_t magic_mask = UINT32_C (126 ) <<23 ; 410const float magic_bias = 0.5f ; 411const float denormalized_value = fp32_from_bits ((two_w >>17 ) |magic_mask )- magic_bias ; 412 413const uint32_t denormalized_cutoff = UINT32_C (1 ) <<27 ; 414const uint32_t result = sign | 415 (two_w < denormalized_cutoff ?fp32_to_bits (denormalized_value ) :fp32_to_bits (normalized_value )); 416return 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 ) 421const float scale_to_inf = 0x1.0p+112f ; 422const float scale_to_zero = 0x1.0p-110f ; 423#else 424const float scale_to_inf = fp32_from_bits (UINT32_C (0x77800000 )); 425const float scale_to_zero = fp32_from_bits (UINT32_C (0x08800000 )); 426#endif 427float base = (fabsf (f )* scale_to_inf )* scale_to_zero ; 428 429const uint32_t w = fp32_to_bits (f ); 430const uint32_t shl1_w = w + w ; 431const uint32_t sign = w & UINT32_C (0x80000000 ); 432uint32_t bias = shl1_w & UINT32_C (0xFF000000 ); 433if (bias < UINT32_C (0x71000000 )) { 434bias = UINT32_C (0x71000000 ); 435 } 436 437base = fp32_from_bits ((bias >>1 )+ UINT32_C (0x07800000 ))+ base ; 438const uint32_t bits = fp32_to_bits (base ); 439const uint32_t exp_bits = (bits >>13 )& UINT32_C (0x00007C00 ); 440const uint32_t mantissa_bits = bits & UINT32_C (0x00000FFF ); 441const uint32_t nonsign = exp_bits + mantissa_bits ; 442return (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 ) { 452uint32_t bits ;// Stores the raw bit representation of the float 453 454// Handle special case for minimum exponent (denormalized float) 455if (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) 461bits = 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) 473else { 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) 478bits = (uint32_t )x <<23 ; 479 } 480 481float result ;// Final float value 482// Safely reinterpret bit pattern as float without type-punning issues 483memcpy (& result ,& bits ,sizeof (float )); 484return 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 ) { 490uint32_t bits ; 491 492// For x < 2: use precomputed denormal patterns 493if (x < 2 ) { 494// 0x00200000 = 2^(-128), 0x00400000 = 2^(-127) 495bits = 0x00200000 <<x ; 496 } 497// For x >= 2: normalized exponent adjustment 498else { 499// 0.5 * 2^(x-127) = 2^(x-128) = normalized with exponent (x-1) 500bits = (uint32_t )(x - 1 ) <<23 ; 501 } 502// Note: NaNs are not handled here 503 504float result ; 505memcpy (& result ,& bits ,sizeof (float )); 506return 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 ) { 515if (x == 0 || x == 0x7F ) { 516return 0.0f ; 517 } 518int exp = (x >>3 )& 0xF ; 519int man = x & 0x7 ; 520float raw ; 521if (exp == 0 ) { 522raw = ldexpf ((float )man ,-9 ); 523 }else { 524raw = ldexpf (1.0f + (float )man /8.0f ,exp - 7 ); 525 } 526return raw * 0.5f ; 527} 528 529static inline uint8_t ggml_fp32_to_ue4m3 (float x ) { 530if (!(x > 0.0f )) { 531return 0 ; 532 } 533if (x > 448.0f ) { 534x = 448.0f ; 535 } 536uint32_t bits ; 537memcpy (& bits ,& x ,4 ); 538int fp32_exp = ((bits >>23 )& 0xFF )- 127 ; 539int fp32_man = (bits >>20 )& 0x7 ; 540int ue4m3_exp = fp32_exp + 7 ; 541if (ue4m3_exp <=0 ) { 542// subnormal: value = man * 2^-9, man = round(x * 2^9) 543int man = (int ) (x * 512.0f + 0.5f ); 544if (man > 7 ) { 545man = 7 ; 546 } 547if (man < 1 ) { 548return 0 ; 549 } 550return (uint8_t )man ; 551 } 552if (ue4m3_exp >=15 ) { 553return 0x7E ; 554 } 555int round_bit = (bits >>19 )& 1 ; 556int ue4m3_man = fp32_man + round_bit ; 557if (ue4m3_man > 7 ) { 558ue4m3_man = 0 ; 559ue4m3_exp ++ ; 560if (ue4m3_exp >=15 ) { 561return 0x7E ; 562 } 563 } 564return (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 ) { 607union { 608float f ; 609uint32_t i ; 610 }u ; 611u .i = (uint32_t )h .bits <<16 ; 612return 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 ) { 624ggml_bf16_t h ; 625union { 626float f ; 627uint32_t i ; 628 }u ; 629u .f = s ; 630if ((u .i & 0x7fffffff )> 0x7f800000 ) {/* nan */ 631h .bits = (u .i >>16 ) |64 ;/* force to quiet */ 632return h ; 633 } 634h .bits = (u .i + (0x7fff + ((u .i >>16 )& 1 ))) >>16 ; 635return 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 ) { 642const struct ggml_tensor * node = cgraph -> nodes [node_idx ]; 643 644size_t hash_pos = ggml_hash_find (& cgraph -> visited_hash_set ,node ); 645if (!ggml_bitset_get (cgraph -> visited_hash_set .used ,hash_pos )) { 646return 0 ; 647 } 648return 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 ) { 654const struct ggml_tensor * node = cgraph -> nodes [node_idx ]; 655 656// check the use count against how many we're replacing 657if (ggml_node_get_use_count (cgraph ,node_idx )!= n_uses ) { 658return false; 659 } 660 661// if node is a view, some other node might be using the intermediate result 662// via the view source. 663if (node -> view_src ) { 664return false; 665 } 666 667// If the user requested output for the node, can't fuse 668if (node -> flags & GGML_TENSOR_FLAG_OUTPUT ) { 669return false; 670 } 671 672return 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 ) { 682for (int i = 0 ;i < num_ops ;++ i ) { 683if (node_idxs [i ] >=cgraph -> n_nodes ) { 684return false; 685 } 686 687struct ggml_tensor * node = cgraph -> nodes [node_idxs [i ]]; 688if (node -> op != ops [i ]) { 689return false; 690 } 691if ((node -> flags & GGML_TENSOR_FLAG_COMPUTE )== 0 ) { 692return false; 693 } 694if (i < num_ops - 1 && !ggml_node_has_n_uses (cgraph ,node_idxs [i ],1 )) { 695return false; 696 } 697if (i > 0 ) { 698struct ggml_tensor * prev = cgraph -> nodes [node_idxs [i - 1 ]]; 699if (node -> src [0 ]!= prev && node -> src [1 ]!= prev ) { 700return false; 701 } 702if (!ggml_are_same_shape (node ,prev )) { 703return false; 704 } 705 } 706 } 707return 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 ) { 712assert (num_ops < 32 ); 713 714if (node_idx + num_ops > cgraph -> n_nodes ) { 715return false; 716 } 717 718int idxs [32 ]; 719for (int i = 0 ;i < num_ops ;++ i ) { 720idxs [i ]= node_idx + i ; 721 } 722 723return ggml_can_fuse_ext (cgraph ,idxs ,ops ,num_ops ); 724} 725 726GGML_API bool ggml_can_fuse_subgraph_ext (const struct ggml_cgraph * cgraph , 727const int * node_idxs , 728int count , 729const enum ggml_op * ops , 730const int * outputs , 731int 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 , 737int node_idx , 738int count , 739const enum ggml_op * ops , 740const int * outputs , 741int num_outputs ) { 742GGML_ASSERT (count < 32 ); 743if (node_idx + count > cgraph -> n_nodes ) { 744return false; 745 } 746 747int idxs [32 ]; 748 749for (int i = 0 ;i < count ;++ i ) { 750idxs [i ]= node_idx + i ; 751 } 752 753return 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 ) { 767return ggml_can_fuse (cgraph ,node_idx ,ops .begin (), (int )ops .size ()); 768} 769 770inline bool ggml_can_fuse_subgraph (const struct ggml_cgraph * cgraph , 771int start_idx , 772std ::initializer_list < enum ggml_op > ops , 773std ::initializer_list < int > outputs = {}) { 774return 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 , 779int start_idx , 780std ::initializer_list < std ::array < int ,3 >>edges ) { 781for (const auto& edge :edges ) { 782int dst_node = edge [0 ]; 783int src_idx = edge [1 ]; 784int src_node = edge [2 ]; 785if (cgraph -> nodes [start_idx + dst_node ]-> src [src_idx ]!= cgraph -> nodes [start_idx + src_node ]) { 786return false; 787 } 788 } 789return 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