Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-cpu/ggml-cpu.c # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-cpu / ggml-cpu.c` 3962 lines ยท 133583 bytes Raw Blame History 1 #define _CRT_SECURE_NO_DEPRECATE // Disables "unsafe" warnings on Windows 2 #define _USE_MATH_DEFINES // For M_PI on MSVC 3 4 #include "ggml-backend-impl.h" 5 #include "ggml-backend.h" 6 #include "traits.h" 7 #include "ggml-cpu-impl.h" 8 #include "ggml-impl.h" 9 #include "quants.h" 10 #include "ggml-threading.h" 11 #include "unary-ops.h" 12 #include "binary-ops.h" 13 #include "vec.h" 14 #include "ops.h" 15 #include "ggml.h" 16 #include "common.h" 17 #include "tiled/tiled.h" 18 19 #if defined(_MSC_VER) || defined(__MINGW32__) 20 #include // using malloc.h with MSC/MINGW 21 #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) 22 #include 23 #endif 24 25 #include 26 #include 27 #include 28 #include 29 #include 30 #include 31 #include 32 #include 33 #include 34 #include 35 #include 36 #include 37 #include 38 #if defined(__gnu_linux__) 39 #include 40 #endif 41 42 #ifdef GGML_USE_OPENMP 43 #include 44 #endif 45 46 #if defined(__ARM_FEATURE_SVE) || defined(__ARM_FEATURE_MATMUL_INT8) 47 #undef GGML_USE_LLAMAFILE 48 #endif 49 50 #ifdef GGML_USE_LLAMAFILE 51 #include "llamafile/sgemm.h" 52 #endif 53 54 #ifdef GGML_USE_CPU_RISCV64_SPACEMIT 55 # include "spacemit/ime.h" 56 #endif 57 58 // Note: once we move threading into a separate C++ file 59 // will use std::hardware_destructive_interference_size instead of hardcoding it here 60 // and we'll use C++ attribute syntax. 61 #define GGML_CACHE_LINE 64 62 63 #if defined(__clang__) || defined(__GNUC__) 64 #define GGML_CACHE_ALIGN __attribute__((aligned(GGML_CACHE_LINE))) 65 #endif 66 67 #if defined(__has_feature) 68 #if __has_feature(thread_sanitizer) 69 #define GGML_TSAN_ENABLED 1 70 #endif 71 #else // __has_feature 72 #if defined(__SANITIZE_THREAD__) 73 #define GGML_TSAN_ENABLED 1 74 #endif 75 #endif // __has_feature 76 77 #define UNUSED GGML_UNUSED 78 #define SWAP(x, y, T) do { T SWAP = x; (x) = y; (y) = SWAP; } while (0) 79 80 // precomputed f32 table for f16 (256 KB) (simd-mappings.h) 81 float ggml_table_f32_f16[1 << 16]; 82 83 // precomputed f32 table for e8m0 half (1 KB) (simd-mappings.h) 84 float ggml_table_f32_e8m0_half[1 << 8]; 85 86 // precomputed f32 table for ue4m3 (1 KB) (simd-mappings.h) 87 float ggml_table_f32_ue4m3[1 << 8]; 88 89 // Signed FP8 needs its own table: UE4M3 ignores the sign, halves values for NVFP4, and maps NaN to zero. 90 float ggml_table_f32_f8_e4m3[1 << 8]; 91 92 #if defined(__ARM_ARCH) 93 struct ggml_arm_arch_features_type { 94 int sve_cnt; 95 } ggml_arm_arch_features = { 0 }; 96 #endif 97 98 #if defined(__riscv) 99 struct ggml_riscv_arch_features_type { 100 int rvv_vlen; 101 } ggml_riscv_arch_features = { 0 }; 102 #endif 103 104 #if defined(_WIN32) 105 106 #define WIN32_LEAN_AND_MEAN 107 #ifndef NOMINMAX 108 #define NOMINMAX 109 #endif 110 #include 111 112 #if defined(_MSC_VER) && !defined(__clang__) 113 #define GGML_CACHE_ALIGN __declspec(align(GGML_CACHE_LINE)) 114 115 typedef volatile LONG atomic_int; 116 typedef atomic_int atomic_bool; 117 typedef atomic_int atomic_flag; 118 119 #define ATOMIC_FLAG_INIT 0 120 121 typedef enum { 122 memory_order_relaxed, 123 memory_order_consume, 124 memory_order_acquire, 125 memory_order_release, 126 memory_order_acq_rel, 127 memory_order_seq_cst 128 } memory_order; 129 130 static void atomic_store(atomic_int * ptr, LONG val) { 131 InterlockedExchange(ptr, val); 132 } 133 static void atomic_store_explicit(atomic_int * ptr, LONG val, memory_order mo) { 134 // TODO: add support for explicit memory order 135 InterlockedExchange(ptr, val); 136 } 137 static LONG atomic_load(atomic_int * ptr) { 138 return InterlockedCompareExchange(ptr, 0, 0); 139 } 140 static LONG atomic_load_explicit(atomic_int * ptr, memory_order mo) { 141 // TODO: add support for explicit memory order 142 return InterlockedCompareExchange(ptr, 0, 0); 143 } 144 static LONG atomic_fetch_add(atomic_int * ptr, LONG inc) { 145 return InterlockedExchangeAdd(ptr, inc); 146 } 147 static LONG atomic_fetch_add_explicit(atomic_int * ptr, LONG inc, memory_order mo) { 148 // TODO: add support for explicit memory order 149 return InterlockedExchangeAdd(ptr, inc); 150 } 151 static atomic_bool atomic_flag_test_and_set(atomic_flag * ptr) { 152 return InterlockedExchange(ptr, 1); 153 } 154 static void atomic_flag_clear(atomic_flag * ptr) { 155 InterlockedExchange(ptr, 0); 156 } 157 static void atomic_thread_fence(memory_order mo) { 158 MemoryBarrier(); 159 } 160 #else // clang 161 #include 162 #endif 163 164 typedef HANDLE pthread_t; 165 166 typedef DWORD thread_ret_t; 167 static int pthread_create(pthread_t * out, void * unused, thread_ret_t(*func)(void *), void * arg) { 168 (void) unused; 169 HANDLE handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, NULL); 170 if (handle == NULL) 171 { 172 return EAGAIN; 173 } 174 175 *out = handle; 176 return 0; 177 } 178 179 static int pthread_join(pthread_t thread, void * unused) { 180 (void) unused; 181 int ret = (int) WaitForSingleObject(thread, INFINITE); 182 CloseHandle(thread); 183 return ret; 184 } 185 186 static int sched_yield (void) { 187 Sleep (0); 188 return 0; 189 } 190 #else 191 192 #include 193 #include 194 #include 195 #if defined(__FreeBSD__) 196 #include 197 #endif 198 199 typedef void * thread_ret_t; 200 201 #include 202 #include 203 #include 204 205 #endif 206 207 typedef pthread_t ggml_thread_t; 208 209 #define GGML_THREADPOOL_N_THREADS_MASK (0xffffU) 210 #define GGML_THREADPOOL_N_THREADS_BITS (16) 211 212 #if defined(__APPLE__) 213 #include 214 #include 215 #include 216 #endif 217 218 static const struct ggml_type_traits_cpu type_traits_cpu[GGML_TYPE_COUNT] = { 219 [GGML_TYPE_F32] = { 220 .from_float = (ggml_from_float_t) ggml_cpu_fp32_to_fp32, 221 .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f32, 222 .vec_dot_type = GGML_TYPE_F32, 223 .nrows = 1, 224 }, 225 [GGML_TYPE_F16] = { 226 .from_float = (ggml_from_float_t) ggml_cpu_fp32_to_fp16, 227 .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_f16, 228 .vec_dot_type = GGML_TYPE_F16, 229 .nrows = 1, 230 }, 231 [GGML_TYPE_Q1_0] = { 232 .from_float = quantize_row_q1_0, 233 .vec_dot = ggml_vec_dot_q1_0_q8_0, 234 .vec_dot_type = GGML_TYPE_Q8_0, 235 .nrows = 1, 236 }, 237 [GGML_TYPE_Q2_0] = { 238 .from_float = quantize_row_q2_0, 239 .vec_dot = ggml_vec_dot_q2_0_q8_0, 240 .vec_dot_type = GGML_TYPE_Q8_0, 241 .nrows = 1, 242 }, 243 [GGML_TYPE_Q4_0] = { 244 .from_float = quantize_row_q4_0, 245 .vec_dot = ggml_vec_dot_q4_0_q8_0, 246 .vec_dot_type = GGML_TYPE_Q8_0, 247 #if defined (__ARM_FEATURE_MATMUL_INT8) 248 .nrows = 2, 249 #else 250 .nrows = 1, 251 #endif 252 }, 253 [GGML_TYPE_Q4_1] = { 254 .from_float = quantize_row_q4_1, 255 .vec_dot = ggml_vec_dot_q4_1_q8_1, 256 .vec_dot_type = GGML_TYPE_Q8_1, 257 #if defined (__ARM_FEATURE_MATMUL_INT8) 258 .nrows = 2, 259 #else 260 .nrows = 1, 261 #endif 262 }, 263 [GGML_TYPE_Q5_0] = { 264 .from_float = quantize_row_q5_0, 265 .vec_dot = ggml_vec_dot_q5_0_q8_0, 266 .vec_dot_type = GGML_TYPE_Q8_0, 267 .nrows = 1, 268 }, 269 [GGML_TYPE_Q5_1] = { 270 .from_float = quantize_row_q5_1, 271 .vec_dot = ggml_vec_dot_q5_1_q8_1, 272 .vec_dot_type = GGML_TYPE_Q8_1, 273 .nrows = 1, 274 }, 275 [GGML_TYPE_Q8_0] = { 276 .from_float = quantize_row_q8_0, 277 .vec_dot = ggml_vec_dot_q8_0_q8_0, 278 .vec_dot_type = GGML_TYPE_Q8_0, 279 #if defined (__ARM_FEATURE_MATMUL_INT8) 280 .nrows = 2, 281 #else 282 .nrows = 1, 283 #endif 284 }, 285 [GGML_TYPE_Q8_1] = { 286 .from_float = quantize_row_q8_1, 287 .vec_dot_type = GGML_TYPE_Q8_1, 288 .nrows = 1, 289 }, 290 [GGML_TYPE_MXFP4] = { 291 .from_float = quantize_row_mxfp4, 292 .vec_dot = ggml_vec_dot_mxfp4_q8_0, 293 .vec_dot_type = GGML_TYPE_Q8_0, 294 .nrows = 1, 295 }, 296 [GGML_TYPE_NVFP4] = { 297 .from_float = quantize_row_nvfp4, 298 .vec_dot = ggml_vec_dot_nvfp4_q8_0, 299 .vec_dot_type = GGML_TYPE_Q8_0, 300 .nrows = 1, 301 }, 302 [GGML_TYPE_F8_E4M3] = { 303 .from_float = quantize_row_f8_e4m3, 304 .vec_dot = ggml_vec_dot_f8_e4m3_f32, 305 .vec_dot_type = GGML_TYPE_F32, 306 .nrows = 1, 307 }, 308 [GGML_TYPE_Q2_K] = { 309 .from_float = quantize_row_q2_K, 310 .vec_dot = ggml_vec_dot_q2_K_q8_K, 311 .vec_dot_type = GGML_TYPE_Q8_K, 312 .nrows = 1, 313 }, 314 [GGML_TYPE_Q3_K] = { 315 .from_float = quantize_row_q3_K, 316 .vec_dot = ggml_vec_dot_q3_K_q8_K, 317 .vec_dot_type = GGML_TYPE_Q8_K, 318 .nrows = 1, 319 }, 320 [GGML_TYPE_Q4_K] = { 321 .from_float = quantize_row_q4_K, 322 .vec_dot = ggml_vec_dot_q4_K_q8_K, 323 .vec_dot_type = GGML_TYPE_Q8_K, 324 #if defined (__ARM_FEATURE_MATMUL_INT8) 325 .nrows = 2, 326 #else 327 .nrows = 1, 328 #endif 329 }, 330 [GGML_TYPE_Q5_K] = { 331 .from_float = quantize_row_q5_K, 332 .vec_dot = ggml_vec_dot_q5_K_q8_K, 333 .vec_dot_type = GGML_TYPE_Q8_K, 334 .nrows = 1, 335 }, 336 [GGML_TYPE_Q6_K] = { 337 .from_float = quantize_row_q6_K, 338 .vec_dot = ggml_vec_dot_q6_K_q8_K, 339 .vec_dot_type = GGML_TYPE_Q8_K, 340 #if defined (__ARM_FEATURE_MATMUL_INT8) 341 .nrows = 2, 342 #else 343 .nrows = 1, 344 #endif 345 }, 346 [GGML_TYPE_IQ2_XXS] = { 347 .from_float = NULL, 348 .vec_dot = ggml_vec_dot_iq2_xxs_q8_K, 349 .vec_dot_type = GGML_TYPE_Q8_K, 350 .nrows = 1, 351 }, 352 [GGML_TYPE_IQ2_XS] = { 353 .from_float = NULL, 354 .vec_dot = ggml_vec_dot_iq2_xs_q8_K, 355 .vec_dot_type = GGML_TYPE_Q8_K, 356 .nrows = 1, 357 }, 358 [GGML_TYPE_IQ3_XXS] = { 359 // NOTE: from_float for iq3 and iq2_s was removed because these quants require initialization in ggml_quantize_init 360 //.from_float = quantize_row_iq3_xxs, 361 .vec_dot = ggml_vec_dot_iq3_xxs_q8_K, 362 .vec_dot_type = GGML_TYPE_Q8_K, 363 .nrows = 1, 364 }, 365 [GGML_TYPE_IQ3_S] = { 366 //.from_float = quantize_row_iq3_s, 367 .vec_dot = ggml_vec_dot_iq3_s_q8_K, 368 .vec_dot_type = GGML_TYPE_Q8_K, 369 .nrows = 1, 370 }, 371 [GGML_TYPE_IQ2_S] = { 372 //.from_float = quantize_row_iq2_s, 373 .vec_dot = ggml_vec_dot_iq2_s_q8_K, 374 .vec_dot_type = GGML_TYPE_Q8_K, 375 .nrows = 1, 376 }, 377 [GGML_TYPE_IQ1_S] = { 378 .from_float = NULL, 379 .vec_dot = ggml_vec_dot_iq1_s_q8_K, 380 .vec_dot_type = GGML_TYPE_Q8_K, 381 .nrows = 1, 382 }, 383 [GGML_TYPE_IQ1_M] = { 384 .from_float = NULL, 385 .vec_dot = ggml_vec_dot_iq1_m_q8_K, 386 .vec_dot_type = GGML_TYPE_Q8_K, 387 .nrows = 1, 388 }, 389 [GGML_TYPE_IQ4_NL] = { 390 .from_float = quantize_row_iq4_nl, 391 .vec_dot = ggml_vec_dot_iq4_nl_q8_0, 392 .vec_dot_type = GGML_TYPE_Q8_0, 393 .nrows = 1, 394 }, 395 [GGML_TYPE_IQ4_XS] = { 396 .from_float = quantize_row_iq4_xs, 397 .vec_dot = ggml_vec_dot_iq4_xs_q8_K, 398 .vec_dot_type = GGML_TYPE_Q8_K, 399 .nrows = 1, 400 }, 401 [GGML_TYPE_Q8_K] = { 402 .from_float = quantize_row_q8_K, 403 }, 404 [GGML_TYPE_BF16] = { 405 .from_float = (ggml_from_float_t) ggml_cpu_fp32_to_bf16, 406 .vec_dot = (ggml_vec_dot_t) ggml_vec_dot_bf16, 407 .vec_dot_type = GGML_TYPE_BF16, 408 .nrows = 1, 409 }, 410 [GGML_TYPE_TQ1_0] = { 411 .from_float = quantize_row_tq1_0, 412 .vec_dot = ggml_vec_dot_tq1_0_q8_K, 413 .vec_dot_type = GGML_TYPE_Q8_K, 414 .nrows = 1, 415 }, 416 [GGML_TYPE_TQ2_0] = { 417 .from_float = quantize_row_tq2_0, 418 .vec_dot = ggml_vec_dot_tq2_0_q8_K, 419 .vec_dot_type = GGML_TYPE_Q8_K, 420 .nrows = 1, 421 }, 422 [GGML_TYPE_I32] = { 423 .from_float = (ggml_from_float_t) ggml_cpu_fp32_to_i32, 424 }, 425 }; 426 427 const struct ggml_type_traits_cpu * ggml_get_type_traits_cpu(enum ggml_type type) { 428 return &type_traits_cpu[type]; 429 } 430 431 // 432 // Threading defs 433 // 434 435 typedef pthread_t ggml_thread_t; 436 437 #if defined(_WIN32) 438 439 typedef CONDITION_VARIABLE ggml_cond_t; 440 typedef SRWLOCK ggml_mutex_t; 441 442 #define ggml_mutex_init(m) InitializeSRWLock(m) 443 #define ggml_mutex_destroy(m) 444 #define ggml_mutex_lock(m) AcquireSRWLockExclusive(m) 445 #define ggml_mutex_unlock(m) ReleaseSRWLockExclusive(m) 446 #define ggml_mutex_lock_shared(m) AcquireSRWLockShared(m) 447 #define ggml_mutex_unlock_shared(m) ReleaseSRWLockShared(m) 448 449 #define ggml_cond_init(c) InitializeConditionVariable(c) 450 #define ggml_cond_destroy(c) 451 #define ggml_cond_wait(c, m) SleepConditionVariableSRW(c, m, INFINITE, CONDITION_VARIABLE_LOCKMODE_SHARED) 452 #define ggml_cond_broadcast(c) WakeAllConditionVariable(c) 453 454 #define ggml_thread_create pthread_create 455 #define ggml_thread_join pthread_join 456 457 #else 458 459 typedef pthread_cond_t ggml_cond_t; 460 typedef pthread_mutex_t ggml_mutex_t; 461 462 #define ggml_mutex_init(m) pthread_mutex_init(m, NULL) 463 #define ggml_mutex_destroy(m) pthread_mutex_destroy(m) 464 #define ggml_mutex_lock(m) pthread_mutex_lock(m) 465 #define ggml_mutex_unlock(m) pthread_mutex_unlock(m) 466 #define ggml_mutex_lock_shared(m) pthread_mutex_lock(m) 467 #define ggml_mutex_unlock_shared(m) pthread_mutex_unlock(m) 468 469 #define ggml_lock_init(x) UNUSED(x) 470 #define ggml_lock_destroy(x) UNUSED(x) 471 #if defined(__x86_64__) || (defined(_MSC_VER) && defined(_M_AMD64) && !defined(_M_ARM64EC)) 472 #define ggml_lock_lock(x) _mm_pause() 473 #else 474 #define ggml_lock_lock(x) UNUSED(x) 475 #endif 476 #define ggml_lock_unlock(x) UNUSED(x) 477 478 #define GGML_LOCK_INITIALIZER 0 479 #define ggml_cond_init(c) pthread_cond_init(c, NULL) 480 #define ggml_cond_destroy(c) pthread_cond_destroy(c) 481 #define ggml_cond_wait(c, m) pthread_cond_wait(c, m) 482 #define ggml_cond_broadcast(c) pthread_cond_broadcast(c) 483 484 #define ggml_thread_create pthread_create 485 #define ggml_thread_join pthread_join 486 487 #endif 488 489 // Threadpool def 490 struct ggml_threadpool { 491 ggml_mutex_t mutex; // mutex for cond.var 492 ggml_cond_t cond; // cond.var for waiting for new work 493 494 struct ggml_cgraph * cgraph; 495 struct ggml_cplan * cplan; 496 497 // synchronization primitives 498 atomic_int n_graph; // updated when there is work to be done (i.e each graph) holds graph and active thread counts. 499 atomic_int GGML_CACHE_ALIGN n_barrier; 500 atomic_int GGML_CACHE_ALIGN n_barrier_passed; 501 atomic_int GGML_CACHE_ALIGN current_chunk; // currently processing chunk during Mat_Mul, shared between all the threads. 502 503 // these are atomic as an annotation for thread-sanitizer 504 atomic_bool stop; // Used for stopping the threadpool altogether 505 atomic_bool pause; // Used for pausing the threadpool or individual threads 506 atomic_int abort; // Used for aborting processing of a graph 507 508 struct ggml_compute_state * workers; // per thread state 509 int n_threads; // Number of threads in the pool 510 int32_t prio; // Scheduling priority 511 uint32_t poll; // Polling level (0 - no polling) 512 513 enum ggml_status ec; 514 }; 515 516 // Per-thread state 517 struct ggml_compute_state { 518 #ifndef GGML_USE_OPENMP 519 ggml_thread_t thrd; 520 int last_graph; 521 bool pending; 522 #endif 523 bool cpumask[GGML_MAX_N_THREADS]; 524 struct ggml_threadpool * threadpool; 525 int ith; 526 }; 527 528 // Helpers for polling loops 529 #if defined(__aarch64__) && ( defined(__clang__) || defined(__GNUC__) ) 530 static inline void ggml_thread_cpu_relax(void) { 531 __asm__ volatile("yield" ::: "memory"); 532 } 533 #elif defined(__x86_64__) 534 static inline void ggml_thread_cpu_relax(void) { 535 _mm_pause(); 536 } 537 #elif defined(__riscv) 538 static inline void ggml_thread_cpu_relax(void) { 539 #ifdef __riscv_zihintpause 540 __asm__ __volatile__ ("pause"); 541 #else 542 /* Encoding of the pause instruction */ 543 __asm__ __volatile__ (".4byte 0x100000F"); 544 #endif 545 } 546 #else 547 static inline void ggml_thread_cpu_relax(void) {;} 548 #endif 549 550 // 551 // NUMA support 552 // 553 554 #define GGML_NUMA_MAX_NODES 8 555 #define GGML_NUMA_MAX_CPUS 512 556 557 struct ggml_numa_node { 558 uint32_t cpus[GGML_NUMA_MAX_CPUS]; // hardware threads on this node 559 uint32_t n_cpus; 560 }; 561 562 struct ggml_numa_nodes { 563 enum ggml_numa_strategy numa_strategy; 564 struct ggml_numa_node nodes[GGML_NUMA_MAX_NODES]; 565 uint32_t n_nodes; 566 uint32_t total_cpus; // hardware threads on system 567 uint32_t current_node; // node on which main process is execting 568 #if defined(__gnu_linux__) 569 cpu_set_t cpuset; // cpuset from numactl 570 #else 571 uint32_t cpuset; // no NUMA support outside of Linux at this time. Use a portable datatype 572 #endif 573 }; 574 575 // 576 // ggml state 577 // 578 579 struct ggml_state { 580 struct ggml_numa_nodes numa; 581 }; 582 583 static struct ggml_state g_state = {0}; 584 585 void ggml_barrier(struct ggml_threadpool * tp) { 586 int n_threads = atomic_load_explicit(&tp->n_graph, memory_order_relaxed) & GGML_THREADPOOL_N_THREADS_MASK; 587 if (n_threads == 1) { 588 return; 589 } 590 591 #ifdef GGML_USE_OPENMP 592 #pragma omp barrier 593 #else 594 int n_passed = atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed); 595 596 // enter barrier (full seq-cst fence) 597 int n_barrier = atomic_fetch_add_explicit(&tp->n_barrier, 1, memory_order_seq_cst); 598 599 if (n_barrier == (n_threads - 1)) { 600 // last thread 601 atomic_store_explicit(&tp->n_barrier, 0, memory_order_relaxed); 602 603 // exit barrier (full seq-cst fence) 604 atomic_fetch_add_explicit(&tp->n_barrier_passed, 1, memory_order_seq_cst); 605 return; 606 } 607 608 // wait for other threads 609 while (atomic_load_explicit(&tp->n_barrier_passed, memory_order_relaxed) == n_passed) { 610 ggml_thread_cpu_relax(); 611 } 612 613 // exit barrier (full seq-cst fence) 614 // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead 615 #ifdef GGML_TSAN_ENABLED 616 atomic_fetch_add_explicit(&tp->n_barrier_passed, 0, memory_order_seq_cst); 617 #else 618 atomic_thread_fence(memory_order_seq_cst); 619 #endif 620 #endif 621 } 622 623 void ggml_threadpool_chunk_set(struct ggml_threadpool * tp, int value) { 624 atomic_store_explicit(&tp->current_chunk, value, memory_order_relaxed); 625 } 626 627 int ggml_threadpool_chunk_add(struct ggml_threadpool * tp, int value) { 628 return atomic_fetch_add_explicit(&tp->current_chunk, value, memory_order_relaxed); 629 } 630 631 #if defined(__gnu_linux__) 632 static cpu_set_t ggml_get_numa_affinity(void) { 633 cpu_set_t cpuset; 634 pthread_t thread; 635 thread = pthread_self(); 636 CPU_ZERO(&cpuset); 637 pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset); 638 return cpuset; 639 } 640 #else 641 static uint32_t ggml_get_numa_affinity(void) { 642 return 0; // no NUMA support 643 } 644 #endif 645 646 void ggml_numa_init(enum ggml_numa_strategy numa_flag) { 647 if (g_state.numa.n_nodes > 0) { 648 fprintf(stderr, "ggml_numa_init: NUMA already initialized\n"); 649 650 return; 651 } 652 653 #if defined(__gnu_linux__) 654 struct stat st; 655 char path[256]; 656 int rv; 657 658 // set numa scheme 659 g_state.numa.numa_strategy = numa_flag; 660 661 GGML_PRINT_DEBUG("numa strategy %u\n",g_state.numa.numa_strategy); 662 663 g_state.numa.cpuset = ggml_get_numa_affinity(); 664 665 // enumerate nodes 666 while (g_state.numa.n_nodes < GGML_NUMA_MAX_NODES) { 667 rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u", g_state.numa.n_nodes); 668 GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path)); 669 if (stat(path, &st) != 0) { break; } 670 ++g_state.numa.n_nodes; 671 } 672 673 // enumerate CPUs 674 while (g_state.numa.total_cpus < GGML_NUMA_MAX_CPUS) { 675 rv = snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%u", g_state.numa.total_cpus); 676 GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path)); 677 if (stat(path, &st) != 0) { break; } 678 ++g_state.numa.total_cpus; 679 } 680 681 GGML_PRINT_DEBUG("found %u numa nodes, %u CPUs\n", g_state.numa.n_nodes, g_state.numa.total_cpus); 682 683 // figure out which node we're on 684 uint current_cpu; 685 int getcpu_ret = 0; 686 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 33) || defined(__COSMOPOLITAN__) 687 getcpu_ret = getcpu(¤t_cpu, &g_state.numa.current_node); 688 #else 689 // old glibc doesn't have a wrapper for this call. Fall back on direct syscall 690 # if !defined(SYS_getcpu) && defined(SYS_get_cpu) 691 # define SYS_getcpu SYS_get_cpu // some older glibc versions use this name 692 # endif 693 getcpu_ret = syscall(SYS_getcpu, ¤t_cpu, &g_state.numa.current_node); 694 #endif 695 696 if (g_state.numa.n_nodes < 1 || g_state.numa.total_cpus < 1 || getcpu_ret != 0) { 697 g_state.numa.n_nodes = 0; 698 return; 699 } 700 701 GGML_PRINT_DEBUG("found our process on numa node %u, CPU %u\n", g_state.numa.current_node, current_cpu); 702 703 for (uint32_t n = 0; n < g_state.numa.n_nodes; ++n) { 704 struct ggml_numa_node * node = &g_state.numa.nodes[n]; 705 GGML_PRINT_DEBUG("CPUs on node %u:", n); 706 node->n_cpus = 0; 707 for (uint32_t c = 0; c < g_state.numa.total_cpus; ++c) { 708 rv = snprintf(path, sizeof(path), "/sys/devices/system/node/node%u/cpu%u", n, c); 709 GGML_ASSERT(rv > 0 && (unsigned)rv < sizeof(path)); 710 if (stat(path, &st) == 0) { 711 node->cpus[node->n_cpus++] = c; 712 GGML_PRINT_DEBUG(" %u", c); 713 } 714 } 715 GGML_PRINT_DEBUG("\n"); 716 } 717 718 if (ggml_is_numa()) { 719 FILE *fptr = fopen("/proc/sys/kernel/numa_balancing", "r"); 720 if (fptr != NULL) { 721 char buf[42]; 722 if (fgets(buf, sizeof(buf), fptr) && strncmp(buf, "0\n", sizeof(buf)) != 0) { 723 GGML_LOG_WARN("/proc/sys/kernel/numa_balancing is enabled, this has been observed to impair performance\n"); 724 } 725 fclose(fptr); 726 } 727 } 728 #else 729 UNUSED(numa_flag); 730 // TODO 731 #endif 732 } 733 734 bool ggml_is_numa(void) { 735 return g_state.numa.n_nodes > 1; 736 } 737 738 #if defined(__ARM_ARCH) 739 #if defined(__aarch64__) && defined(__ARM_FEATURE_SVE) 740 #include 741 static void ggml_init_arm_arch_features(void) { 742 ggml_arm_arch_features.sve_cnt = svcntb(); 743 } 744 #else 745 static void ggml_init_arm_arch_features(void) {} 746 #endif 747 #endif // __ARM_ARCH 748 749 #if defined(__riscv) && defined(__riscv_v) 750 #include 751 static void ggml_init_riscv_arch_features(void) { 752 ggml_riscv_arch_features.rvv_vlen = __riscv_vlenb(); 753 } 754 #else 755 static void ggml_init_riscv_arch_features(void) {} 756 #endif 757 758 struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value) { 759 GGML_ASSERT(!ggml_get_no_alloc(ctx)); 760 761 struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1); 762 763 ggml_set_i32(result, value); 764 765 return result; 766 } 767 768 struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value) { 769 GGML_ASSERT(!ggml_get_no_alloc(ctx)); 770 771 struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1); 772 773 ggml_set_f32(result, value); 774 775 return result; 776 } 777 778 struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value) { 779 const int n = ggml_nrows(tensor); 780 const int nc = tensor->ne[0]; 781 const size_t n1 = tensor->nb[1]; 782 783 char * const data = tensor->data; 784 785 switch (tensor->type) { 786 case GGML_TYPE_I8: 787 { 788 assert(tensor->nb[0] == sizeof(int8_t)); 789 for (int i = 0; i < n; i++) { 790 ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value); 791 } 792 } break; 793 case GGML_TYPE_I16: 794 { 795 assert(tensor->nb[0] == sizeof(int16_t)); 796 for (int i = 0; i < n; i++) { 797 ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value); 798 } 799 } break; 800 case GGML_TYPE_I32: 801 { 802 assert(tensor->nb[0] == sizeof(int32_t)); 803 for (int i = 0; i < n; i++) { 804 ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value); 805 } 806 } break; 807 case GGML_TYPE_F16: 808 { 809 assert(tensor->nb[0] == sizeof(ggml_fp16_t)); 810 for (int i = 0; i < n; i++) { 811 ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_CPU_FP32_TO_FP16(value)); 812 } 813 } break; 814 case GGML_TYPE_BF16: 815 { 816 assert(tensor->nb[0] == sizeof(ggml_fp16_t)); 817 for (int i = 0; i < n; i++) { 818 ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value)); 819 } 820 } break; 821 case GGML_TYPE_F32: 822 { 823 assert(tensor->nb[0] == sizeof(float)); 824 for (int i = 0; i < n; i++) { 825 ggml_vec_set_f32(nc, (float *)(data + i*n1), value); 826 } 827 } break; 828 default: 829 { 830 GGML_ABORT("fatal error"); 831 } 832 } 833 834 return tensor; 835 } 836 837 struct ggml_tensor * ggml_set_f32(struct ggml_tensor * tensor, float value) { 838 const int n = ggml_nrows(tensor); 839 const int nc = tensor->ne[0]; 840 const size_t n1 = tensor->nb[1]; 841 842 char * const data = tensor->data; 843 844 switch (tensor->type) { 845 case GGML_TYPE_I8: 846 { 847 assert(tensor->nb[0] == sizeof(int8_t)); 848 for (int i = 0; i < n; i++) { 849 ggml_vec_set_i8(nc, (int8_t *)(data + i*n1), value); 850 } 851 } break; 852 case GGML_TYPE_I16: 853 { 854 assert(tensor->nb[0] == sizeof(int16_t)); 855 for (int i = 0; i < n; i++) { 856 ggml_vec_set_i16(nc, (int16_t *)(data + i*n1), value); 857 } 858 } break; 859 case GGML_TYPE_I32: 860 { 861 assert(tensor->nb[0] == sizeof(int32_t)); 862 for (int i = 0; i < n; i++) { 863 ggml_vec_set_i32(nc, (int32_t *)(data + i*n1), value); 864 } 865 } break; 866 case GGML_TYPE_F16: 867 { 868 assert(tensor->nb[0] == sizeof(ggml_fp16_t)); 869 for (int i = 0; i < n; i++) { 870 ggml_vec_set_f16(nc, (ggml_fp16_t *)(data + i*n1), GGML_CPU_FP32_TO_FP16(value)); 871 } 872 } break; 873 case GGML_TYPE_BF16: 874 { 875 assert(tensor->nb[0] == sizeof(ggml_bf16_t)); 876 for (int i = 0; i < n; i++) { 877 ggml_vec_set_bf16(nc, (ggml_bf16_t *)(data + i*n1), GGML_FP32_TO_BF16(value)); 878 } 879 } break; 880 case GGML_TYPE_F32: 881 { 882 assert(tensor->nb[0] == sizeof(float)); 883 for (int i = 0; i < n; i++) { 884 ggml_vec_set_f32(nc, (float *)(data + i*n1), value); 885 } 886 } break; 887 default: 888 { 889 GGML_ABORT("fatal error"); 890 } 891 } 892 893 return tensor; 894 } 895 896 int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i) { 897 if (!ggml_is_contiguous(tensor)) { 898 int64_t id[4] = { 0, 0, 0, 0 }; 899 ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]); 900 return ggml_get_i32_nd(tensor, id[0], id[1], id[2], id[3]); 901 } 902 switch (tensor->type) { 903 case GGML_TYPE_I8: 904 { 905 GGML_ASSERT(tensor->nb[0] == sizeof(int8_t)); 906 return ((int8_t *)(tensor->data))[i]; 907 } 908 case GGML_TYPE_I16: 909 { 910 GGML_ASSERT(tensor->nb[0] == sizeof(int16_t)); 911 return ((int16_t *)(tensor->data))[i]; 912 } 913 case GGML_TYPE_I32: 914 { 915 GGML_ASSERT(tensor->nb[0] == sizeof(int32_t)); 916 return ((int32_t *)(tensor->data))[i]; 917 } 918 case GGML_TYPE_F16: 919 { 920 GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t)); 921 return GGML_CPU_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]); 922 } 923 case GGML_TYPE_BF16: 924 { 925 GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t)); 926 return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]); 927 } 928 case GGML_TYPE_F32: 929 { 930 GGML_ASSERT(tensor->nb[0] == sizeof(float)); 931 return ((float *)(tensor->data))[i]; 932 } 933 default: 934 { 935 GGML_ABORT("fatal error"); 936 } 937 } 938 } 939 940 void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value) { 941 if (!ggml_is_contiguous(tensor)) { 942 int64_t id[4] = { 0, 0, 0, 0 }; 943 ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]); 944 ggml_set_i32_nd(tensor, id[0], id[1], id[2], id[3], value); 945 return; 946 } 947 switch (tensor->type) { 948 case GGML_TYPE_I8: 949 { 950 GGML_ASSERT(tensor->nb[0] == sizeof(int8_t)); 951 ((int8_t *)(tensor->data))[i] = value; 952 } break; 953 case GGML_TYPE_I16: 954 { 955 GGML_ASSERT(tensor->nb[0] == sizeof(int16_t)); 956 ((int16_t *)(tensor->data))[i] = value; 957 } break; 958 case GGML_TYPE_I32: 959 { 960 GGML_ASSERT(tensor->nb[0] == sizeof(int32_t)); 961 ((int32_t *)(tensor->data))[i] = value; 962 } break; 963 case GGML_TYPE_F16: 964 { 965 GGML_ASSERT(tensor->nb[0] == sizeof(ggml_fp16_t)); 966 ((ggml_fp16_t *)(tensor->data))[i] = GGML_CPU_FP32_TO_FP16(value); 967 } break; 968 case GGML_TYPE_BF16: 969 { 970 GGML_ASSERT(tensor->nb[0] == sizeof(ggml_bf16_t)); 971 ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value); 972 } break; 973 case GGML_TYPE_F32: 974 { 975 GGML_ASSERT(tensor->nb[0] == sizeof(float)); 976 ((float *)(tensor->data))[i] = value; 977 } break; 978 default: 979 { 980 GGML_ABORT("fatal error"); 981 } 982 } 983 } 984 985 int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) { 986 void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]; 987 switch (tensor->type) { 988 case GGML_TYPE_I8: 989 return ((int8_t *) data)[0]; 990 case GGML_TYPE_I16: 991 return ((int16_t *) data)[0]; 992 case GGML_TYPE_I32: 993 return ((int32_t *) data)[0]; 994 case GGML_TYPE_F16: 995 return GGML_CPU_FP16_TO_FP32(((ggml_fp16_t *) data)[0]); 996 case GGML_TYPE_BF16: 997 return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]); 998 case GGML_TYPE_F32: 999 return ((float *) data)[0]; 1000 default: 1001 GGML_ABORT("fatal error"); 1002 } 1003 } 1004 1005 void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value) { 1006 void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]; 1007 switch (tensor->type) { 1008 case GGML_TYPE_I8: 1009 { 1010 ((int8_t *)(data))[0] = value; 1011 } break; 1012 case GGML_TYPE_I16: 1013 { 1014 ((int16_t *)(data))[0] = value; 1015 } break; 1016 case GGML_TYPE_I32: 1017 { 1018 ((int32_t *)(data))[0] = value; 1019 } break; 1020 case GGML_TYPE_F16: 1021 { 1022 ((ggml_fp16_t *)(data))[0] = GGML_CPU_FP32_TO_FP16(value); 1023 } break; 1024 case GGML_TYPE_BF16: 1025 { 1026 ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value); 1027 } break; 1028 case GGML_TYPE_F32: 1029 { 1030 ((float *)(data))[0] = value; 1031 } break; 1032 default: 1033 { 1034 GGML_ABORT("fatal error"); 1035 } 1036 } 1037 } 1038 1039 float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i) { 1040 if (!ggml_is_contiguous(tensor)) { 1041 int64_t id[4] = { 0, 0, 0, 0 }; 1042 ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]); 1043 return ggml_get_f32_nd(tensor, id[0], id[1], id[2], id[3]); 1044 } 1045 switch (tensor->type) { 1046 case GGML_TYPE_I8: 1047 { 1048 return ((int8_t *)(tensor->data))[i]; 1049 } 1050 case GGML_TYPE_I16: 1051 { 1052 return ((int16_t *)(tensor->data))[i]; 1053 } 1054 case GGML_TYPE_I32: 1055 { 1056 return ((int32_t *)(tensor->data))[i]; 1057 } 1058 case GGML_TYPE_F16: 1059 { 1060 return GGML_CPU_FP16_TO_FP32(((ggml_fp16_t *)(tensor->data))[i]); 1061 } 1062 case GGML_TYPE_BF16: 1063 { 1064 return GGML_BF16_TO_FP32(((ggml_bf16_t *)(tensor->data))[i]); 1065 } 1066 case GGML_TYPE_F32: 1067 { 1068 return ((float *)(tensor->data))[i]; 1069 } 1070 default: 1071 { 1072 GGML_ABORT("fatal error"); 1073 } 1074 } 1075 } 1076 1077 void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value) { 1078 if (!ggml_is_contiguous(tensor)) { 1079 int64_t id[4] = { 0, 0, 0, 0 }; 1080 ggml_unravel_index(tensor, i, &id[0], &id[1], &id[2], &id[3]); 1081 ggml_set_f32_nd(tensor, id[0], id[1], id[2], id[3], value); 1082 return; 1083 } 1084 switch (tensor->type) { 1085 case GGML_TYPE_I8: 1086 { 1087 ((int8_t *)(tensor->data))[i] = value; 1088 } break; 1089 case GGML_TYPE_I16: 1090 { 1091 ((int16_t *)(tensor->data))[i] = value; 1092 } break; 1093 case GGML_TYPE_I32: 1094 { 1095 ((int32_t *)(tensor->data))[i] = value; 1096 } break; 1097 case GGML_TYPE_F16: 1098 { 1099 ((ggml_fp16_t *)(tensor->data))[i] = GGML_CPU_FP32_TO_FP16(value); 1100 } break; 1101 case GGML_TYPE_BF16: 1102 { 1103 ((ggml_bf16_t *)(tensor->data))[i] = GGML_FP32_TO_BF16(value); 1104 } break; 1105 case GGML_TYPE_F32: 1106 { 1107 ((float *)(tensor->data))[i] = value; 1108 } break; 1109 default: 1110 { 1111 GGML_ABORT("fatal error"); 1112 } 1113 } 1114 } 1115 1116 float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3) { 1117 void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]; 1118 switch (tensor->type) { 1119 case GGML_TYPE_I8: 1120 return ((int8_t *) data)[0]; 1121 case GGML_TYPE_I16: 1122 return ((int16_t *) data)[0]; 1123 case GGML_TYPE_I32: 1124 return ((int32_t *) data)[0]; 1125 case GGML_TYPE_F16: 1126 return GGML_CPU_FP16_TO_FP32(((ggml_fp16_t *) data)[0]); 1127 case GGML_TYPE_BF16: 1128 return GGML_BF16_TO_FP32(((ggml_bf16_t *) data)[0]); 1129 case GGML_TYPE_F32: 1130 return ((float *) data)[0]; 1131 default: 1132 GGML_ABORT("fatal error"); 1133 } 1134 } 1135 1136 void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value) { 1137 void * data = (char *) tensor->data + i0*tensor->nb[0] + i1*tensor->nb[1] + i2*tensor->nb[2] + i3*tensor->nb[3]; 1138 switch (tensor->type) { 1139 case GGML_TYPE_I8: 1140 { 1141 ((int8_t *)(data))[0] = value; 1142 } break; 1143 case GGML_TYPE_I16: 1144 { 1145 ((int16_t *)(data))[0] = value; 1146 } break; 1147 case GGML_TYPE_I32: 1148 { 1149 ((int32_t *)(data))[0] = value; 1150 } break; 1151 case GGML_TYPE_F16: 1152 { 1153 ((ggml_fp16_t *)(data))[0] = GGML_CPU_FP32_TO_FP16(value); 1154 } break; 1155 case GGML_TYPE_BF16: 1156 { 1157 ((ggml_bf16_t *)(data))[0] = GGML_FP32_TO_BF16(value); 1158 } break; 1159 case GGML_TYPE_F32: 1160 { 1161 ((float *)(data))[0] = value; 1162 } break; 1163 default: 1164 { 1165 GGML_ABORT("fatal error"); 1166 } 1167 } 1168 } 1169 1170 //////////////////////////////////////////////////////////////////////////////// 1171 1172 // ggml_compute_forward_mul_mat 1173 1174 static void ggml_compute_forward_mul_mat_one_chunk( 1175 const struct ggml_compute_params * params, 1176 struct ggml_tensor * dst, 1177 const enum ggml_type type, 1178 const int64_t num_rows_per_vec_dot, 1179 const int64_t ir0_start, 1180 const int64_t ir0_end, 1181 const int64_t ir1_start, 1182 const int64_t ir1_end) { 1183 1184 const struct ggml_tensor * src0 = dst->src[0]; 1185 const struct ggml_tensor * src1 = dst->src[1]; 1186 1187 GGML_TENSOR_BINARY_OP_LOCALS 1188 1189 const bool src1_cont = ggml_is_contiguous(src1); 1190 1191 ggml_vec_dot_t const vec_dot = type_traits_cpu[type].vec_dot; 1192 enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type; 1193 1194 // broadcast factors 1195 const int64_t r2 = ne12 / ne02; 1196 const int64_t r3 = ne13 / ne03; 1197 1198 //printf("ir0_start = %6lld, ir0_end = %6lld, ir1_start = %6lld, ir1_end = %6lld\n", ir0_start, ir0_end, ir1_start, ir1_end); 1199 1200 // threads with no work simply yield (not sure if it helps) 1201 if (ir0_start >= ir0_end || ir1_start >= ir1_end) { 1202 return; 1203 } 1204 1205 const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata; 1206 const size_t row_size = ggml_row_size(vec_dot_type, ne10); 1207 1208 assert(ne12 % ne02 == 0); 1209 assert(ne13 % ne03 == 0); 1210 1211 // block-tiling attempt 1212 const int64_t blck_0 = 16; 1213 const int64_t blck_1 = 16; 1214 1215 const size_t src1_col_stride = src1_cont || src1->type != vec_dot_type ? row_size : nb11; 1216 1217 // attempt to reduce false-sharing (does not seem to make a difference) 1218 // 16 * 2, accounting for mmla kernels 1219 float tmp[32]; 1220 1221 for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) { 1222 for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) { 1223 for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ir1 += num_rows_per_vec_dot) { 1224 const int64_t i13 = (ir1 / (ne12 * ne1)); 1225 const int64_t i12 = (ir1 - i13 * ne12 * ne1) / ne1; 1226 const int64_t i11 = (ir1 - i13 * ne12 * ne1 - i12 * ne1); 1227 1228 // broadcast src0 into src1 1229 const int64_t i03 = i13 / r3; 1230 const int64_t i02 = i12 / r2; 1231 1232 const int64_t i1 = i11; 1233 const int64_t i2 = i12; 1234 const int64_t i3 = i13; 1235 1236 const char * src0_row = (const char*)src0->data + (0 + i02 * nb02 + i03 * nb03); 1237 1238 // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides 1239 // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using 1240 // the original src1 data pointer, so we should index using the indices directly 1241 // TODO: this is a bit of a hack, we should probably have a better way to handle this 1242 const char * src1_col = (const char*)wdata + 1243 (src1_cont || src1->type != vec_dot_type 1244 ? (i11 + i12 * ne11 + i13 * ne12 * ne11) * row_size 1245 : (i11 * nb11 + i12 * nb12 + i13 * nb13)); 1246 float * dst_col = (float*)((char*)dst->data + (i1 * nb1 + i2 * nb2 + i3 * nb3)); 1247 1248 //for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) { 1249 // vec_dot(ne00, &dst_col[ir0], src0_row + ir0*nb01, src1_col); 1250 //} 1251 1252 for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ir0 += num_rows_per_vec_dot) { 1253 vec_dot(ne00, &tmp[ir0 - iir0], (num_rows_per_vec_dot > 1 ? 16 : 0), src0_row + ir0 * nb01, (num_rows_per_vec_dot > 1 ? nb01 : 0), src1_col, (num_rows_per_vec_dot > 1 ? src1_col_stride : 0), num_rows_per_vec_dot); 1254 } 1255 1256 for (int cn = 0; cn < num_rows_per_vec_dot; ++cn) { 1257 memcpy(&dst_col[iir0 + cn * nb1 / nb0], tmp + (cn * 16), (MIN(iir0 + blck_0, ir0_end) - iir0) * sizeof(float)); 1258 } 1259 } 1260 } 1261 } 1262 } 1263 1264 void ggml_compute_forward_mul_mat( 1265 const struct ggml_compute_params * params, 1266 struct ggml_tensor * dst) { 1267 1268 const struct ggml_tensor * src0 = dst->src[0]; 1269 const struct ggml_tensor * src1 = dst->src[1]; 1270 1271 const int32_t hint = ggml_get_op_params_i32(dst, 1); 1272 if (hint == GGML_HINT_SRC0_IS_HADAMARD && !params->use_ref) { 1273 ggml_compute_forward_fwht(params, dst); 1274 return; 1275 } 1276 1277 // If tiled is supported, it will execute the full op here and we return 1278 if (ggml_compute_forward_mul_mat_tiled(params, dst)) { 1279 return; 1280 } 1281 1282 GGML_TENSOR_BINARY_OP_LOCALS 1283 1284 const int ith = params->ith; 1285 const int nth = params->nth; 1286 1287 enum ggml_type const vec_dot_type = type_traits_cpu[src0->type].vec_dot_type; 1288 ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float; 1289 int64_t const vec_dot_num_rows = type_traits_cpu[src0->type].nrows; 1290 1291 GGML_ASSERT(ne0 == ne01); 1292 GGML_ASSERT(ne1 == ne11); 1293 GGML_ASSERT(ne2 == ne12); 1294 GGML_ASSERT(ne3 == ne13); 1295 1296 // we don't support permuted src0 or src1 1297 GGML_ASSERT(nb00 == ggml_type_size(src0->type)); 1298 GGML_ASSERT(nb10 == ggml_type_size(src1->type)); 1299 1300 // dst cannot be transposed or permuted 1301 GGML_ASSERT(nb0 == sizeof(float)); 1302 GGML_ASSERT(nb0 <= nb1); 1303 GGML_ASSERT(nb1 <= nb2); 1304 GGML_ASSERT(nb2 <= nb3); 1305 1306 // nb01 >= nb00 - src0 is not transposed 1307 // compute by src0 rows 1308 1309 // TODO: extract to "extra_op" 1310 #if GGML_USE_LLAMAFILE 1311 // broadcast factors 1312 const int64_t r2 = ne12 / ne02; 1313 const int64_t r3 = ne13 / ne03; 1314 1315 const bool src1_cont = ggml_is_contiguous(src1); 1316 1317 if (!params->use_ref && src1_cont) { 1318 for (int64_t i13 = 0; i13 < ne13; i13++) 1319 for (int64_t i12 = 0; i12 < ne12; i12++) 1320 if (!llamafile_sgemm(params, 1321 ne01, ne11, ne00/ggml_blck_size(src0->type), 1322 (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03, 1323 nb01/ggml_type_size(src0->type), 1324 (const char *)src1->data + i12*nb12 + i13*nb13, 1325 nb11/ggml_type_size(src1->type), 1326 (char *)dst->data + i12*nb2 + i13*nb3, 1327 nb1/ggml_type_size(dst->type), 1328 src0->type, 1329 src1->type, 1330 dst->type)) 1331 goto UseGgmlGemm1; 1332 return; 1333 } 1334 UseGgmlGemm1:; 1335 #endif 1336 1337 if (src1->type != vec_dot_type) { 1338 char * wdata = params->wdata; 1339 1340 const size_t nbw0 = ggml_type_size(vec_dot_type); 1341 const size_t nbw1 = ggml_row_size(vec_dot_type, ne10); 1342 const size_t nbw2 = nbw1*ne11; 1343 const size_t nbw3 = nbw2*ne12; 1344 1345 assert(params->wsize >= ne13*nbw3); 1346 // src1 is either packed from F32 into vec_dot_type, or widened from F16 or BF16 into the F32 work buffer 1347 const bool widen = src1->type != GGML_TYPE_F32; 1348 1349 GGML_ASSERT(!widen || vec_dot_type == GGML_TYPE_F32); 1350 GGML_ASSERT(!widen || src1->type == GGML_TYPE_F16 || src1->type == GGML_TYPE_BF16); 1351 1352 #if 0 1353 for (int64_t i13 = 0; i13 < ne13; ++i13) { 1354 for (int64_t i12 = 0; i12 < ne12; ++i12) { 1355 for (int64_t i11 = ith; i11 < ne11; i11 += nth) { 1356 from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11), 1357 (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1), 1358 ne10); 1359 } 1360 } 1361 } 1362 #else 1363 const int64_t bs = ggml_blck_size(vec_dot_type); 1364 1365 for (int64_t i13 = 0; i13 < ne13; ++i13) { 1366 for (int64_t i12 = 0; i12 < ne12; ++i12) { 1367 for (int64_t i11 = 0; i11 < ne11; ++i11) { 1368 int64_t ne10_block_start = (ith * ne10/bs) / nth; 1369 int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth; 1370 const void * src1_row = (const char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10; 1371 void * wdata_row = wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0; 1372 1373 const int64_t ne10_block_size = (ne10_block_end - ne10_block_start) * bs; 1374 1375 if (src1->type == GGML_TYPE_F16) { 1376 ggml_cpu_fp16_to_fp32((const ggml_fp16_t *) src1_row, (float *) wdata_row, ne10_block_size); 1377 } else if (src1->type == GGML_TYPE_BF16) { 1378 ggml_cpu_bf16_to_fp32((const ggml_bf16_t *) src1_row, (float *) wdata_row, ne10_block_size); 1379 } else { 1380 from_float((const float *) src1_row, wdata_row, ne10_block_size); 1381 } 1382 } 1383 } 1384 } 1385 #endif 1386 } 1387 1388 if (ith == 0) { 1389 // Every thread starts at ith, so the first unprocessed chunk is nth. This save a bit of coordination right at the start. 1390 atomic_store_explicit(¶ms->threadpool->current_chunk, nth, memory_order_relaxed); 1391 } 1392 1393 ggml_barrier(params->threadpool); 1394 1395 #if GGML_USE_LLAMAFILE 1396 if (!params->use_ref && src1->type != vec_dot_type) { 1397 const void* wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata; 1398 const size_t row_size = ggml_row_size(vec_dot_type, ne10); 1399 1400 for (int64_t i13 = 0; i13 < ne13; i13++) 1401 for (int64_t i12 = 0; i12 < ne12; i12++) 1402 if (!llamafile_sgemm(params, 1403 ne01, ne11, ne00/ggml_blck_size(src0->type), 1404 (const char *)src0->data + i12/r2*nb02 + i13/r3*nb03, 1405 nb01/ggml_type_size(src0->type), 1406 (const char *)wdata + (i12*ne11 + i13*ne12*ne11)*row_size, 1407 row_size/ggml_type_size(vec_dot_type), 1408 (char *)dst->data + i12*nb2 + i13*nb3, 1409 nb1/ggml_type_size(dst->type), 1410 src0->type, 1411 vec_dot_type, 1412 dst->type)) 1413 goto UseGgmlGemm2; 1414 return; 1415 } 1416 UseGgmlGemm2:; 1417 #endif 1418 1419 // This is the size of the first dimension of the result, so we can iterate that way. (see the ASSERT above, these are the same numbers) 1420 const int64_t nr0 = ne0; 1421 1422 // This is the size of the rest of the dimensions of the result 1423 const int64_t nr1 = ne1 * ne2 * ne3; 1424 1425 // Now select a reasonable chunk size. 1426 int chunk_size = 16; 1427 1428 // We need to step up the size if it's small 1429 if (nr0 == 1 || nr1 == 1) { 1430 chunk_size = 64; 1431 } 1432 1433 // distribute the work across the inner or outer loop based on which one is larger 1434 // The number of chunks in the 0/1 dim. 1435 // CEIL(nr0/chunk_size) 1436 int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size; 1437 int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size; 1438 1439 // If the chunking is poor for the number of threads on this setup, scrap the whole plan. Re-chunk it by thread. 1440 // Also, chunking by thread was measured to have perform better on NUMA systems. See https://github.com/ggml-org/llama.cpp/pull/6915 1441 // In theory, chunking should be just as useful on NUMA and non NUMA systems, but testing disagreed with that. 1442 if (nchunk0 * nchunk1 < nth * 4 || ggml_is_numa()) { 1443 // distribute the thread work across the inner or outer loop based on which one is larger 1444 nchunk0 = nr0 > nr1 ? nth : 1; // parallelize by src0 rows 1445 nchunk1 = nr0 > nr1 ? 1 : nth; // parallelize by src1 rows 1446 } 1447 1448 // The number of elements in each chunk 1449 const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0; 1450 const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1; 1451 1452 // The first chunk comes from our thread_id, the rest will get auto-assigned. 1453 int current_chunk = ith; 1454 1455 while (current_chunk < nchunk0 * nchunk1) { 1456 const int64_t ith0 = current_chunk % nchunk0; 1457 const int64_t ith1 = current_chunk / nchunk0; 1458 1459 const int64_t ir0_start = dr0 * ith0; 1460 const int64_t ir0_end = MIN(ir0_start + dr0, nr0); 1461 1462 const int64_t ir1_start = dr1 * ith1; 1463 const int64_t ir1_end = MIN(ir1_start + dr1, nr1); 1464 1465 // dot kernels can handle 1 row and col at a time, but mmla kernels can process 2 rows and cols 1466 int64_t num_rows_per_vec_dot = vec_dot_num_rows; 1467 1468 // these checks are needed to avoid crossing dim1 boundaries 1469 // can be optimized, but the logic would become more complicated, so keeping it like this for simplicity 1470 if ((nr0 % 2 != 0) || (ne11 % 2 != 0) || ((ir0_end - ir0_start) % 2 != 0) || ((ir1_end - ir1_start) % 2 != 0)) { 1471 num_rows_per_vec_dot = 1; 1472 } 1473 ggml_compute_forward_mul_mat_one_chunk(params, dst, src0->type, num_rows_per_vec_dot, ir0_start, ir0_end, ir1_start, ir1_end); 1474 1475 if (nth >= nchunk0 * nchunk1) { 1476 break; 1477 } 1478 1479 current_chunk = atomic_fetch_add_explicit(¶ms->threadpool->current_chunk, 1, memory_order_relaxed); 1480 } 1481 } 1482 1483 // ggml_compute_forward_mul_mat_id 1484 1485 #define MMID_MATRIX_ROW(row_id, i1) matrix_rows[(row_id)*ids->ne[0]*ids->ne[1] + (i1)] 1486 1487 struct mmid_row_mapping { 1488 int32_t i1; 1489 int32_t i2; 1490 }; 1491 1492 static void ggml_compute_forward_mul_mat_id_one_chunk( 1493 struct ggml_tensor * dst, 1494 const struct ggml_tensor * src0, 1495 const struct ggml_tensor * src1, 1496 const struct ggml_tensor * ids, 1497 const int64_t cur_a, 1498 const int64_t ir0_start, 1499 const int64_t ir0_end, 1500 const int64_t ir1_start, 1501 const int64_t ir1_end, 1502 const char * src0_cur, 1503 const struct mmid_row_mapping * matrix_rows, 1504 const size_t row_size, 1505 const bool src1_cont, 1506 const void * wdata) { 1507 1508 GGML_TENSOR_BINARY_OP_LOCALS 1509 1510 const enum ggml_type type = src0->type; 1511 1512 ggml_vec_dot_t const vec_dot = type_traits_cpu[type].vec_dot; 1513 enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type; 1514 1515 const int64_t blck_0 = 16; 1516 const int64_t blck_1 = 16; 1517 1518 float tmp[16]; 1519 1520 for (int64_t iir1 = ir1_start; iir1 < ir1_end; iir1 += blck_1) { 1521 for (int64_t iir0 = ir0_start; iir0 < ir0_end; iir0 += blck_0) { 1522 for (int64_t ir1 = iir1; ir1 < iir1 + blck_1 && ir1 < ir1_end; ++ir1) { 1523 const int64_t _i12 = ir1; // logical row index for this expert 1524 1525 struct mmid_row_mapping row_mapping = MMID_MATRIX_ROW(cur_a, _i12); 1526 const int id = row_mapping.i1; // selected expert index 1527 1528 const int64_t i11 = id % ne11; 1529 const int64_t i12 = row_mapping.i2; // row index in src1 1530 1531 const int64_t i1 = id; // selected expert index 1532 const int64_t i2 = i12; // row 1533 1534 // desc: when src1 is not a contiguous memory block we have to calculate the offset using the strides 1535 // if it is, then we have either copied the data to params->wdata and made it contiguous or we are using 1536 // the original src1 data pointer, so we should index using the indices directly 1537 // TODO: this is a bit of a hack, we should probably have a better way to handle this 1538 const char * src1_col = (const char *) wdata + 1539 (src1_cont || src1->type != vec_dot_type 1540 ? (i11 + i12*ne11)*row_size 1541 : (i11*nb11 + i12*nb12)); 1542 1543 float * dst_col = (float *) ((char *) dst->data + (i1*nb1 + i2*nb2)); 1544 1545 for (int64_t ir0 = iir0; ir0 < iir0 + blck_0 && ir0 < ir0_end; ++ir0) { 1546 vec_dot(ne00, &tmp[ir0 - iir0], 0, src0_cur + ir0*nb01, 0, src1_col, 0, 1); 1547 } 1548 1549 memcpy(&dst_col[iir0], tmp, (MIN(iir0 + blck_0, ir0_end) - iir0)*sizeof(float)); 1550 } 1551 } 1552 } 1553 } 1554 1555 static void * incr_ptr_aligned(void ** p, size_t size, size_t align) { 1556 1557 void * ptr = *p; 1558 ptr = (void *) GGML_PAD((uintptr_t) ptr, align); 1559 *p = (void *) ((char *) ptr + size); 1560 return ptr; 1561 } 1562 1563 static void ggml_compute_forward_mul_mat_id( 1564 const struct ggml_compute_params * params, 1565 struct ggml_tensor * dst) { 1566 1567 const struct ggml_tensor * src0 = dst->src[0]; 1568 const struct ggml_tensor * src1 = dst->src[1]; 1569 const struct ggml_tensor * ids = dst->src[2]; 1570 1571 GGML_TENSOR_BINARY_OP_LOCALS 1572 1573 const int ith = params->ith; 1574 const int nth = params->nth; 1575 1576 const enum ggml_type type = src0->type; 1577 1578 const bool src1_cont = ggml_is_contiguous(src1); 1579 1580 enum ggml_type const vec_dot_type = type_traits_cpu[type].vec_dot_type; 1581 ggml_from_float_t const from_float = type_traits_cpu[vec_dot_type].from_float; 1582 1583 // we don't support permuted src0 or src1 1584 GGML_ASSERT(nb00 == ggml_type_size(type)); 1585 GGML_ASSERT(nb10 == ggml_type_size(src1->type)); 1586 1587 // dst cannot be transposed or permuted 1588 GGML_ASSERT(nb0 == sizeof(float)); 1589 GGML_ASSERT(nb0 <= nb1); 1590 GGML_ASSERT(nb1 <= nb2); 1591 GGML_ASSERT(nb2 <= nb3); 1592 1593 // row groups 1594 const int n_ids = ids->ne[0]; // n_expert_used 1595 const int n_as = ne02; // n_expert 1596 1597 void * wdata_cur = params->wdata; 1598 1599 if (src1->type != vec_dot_type) { 1600 incr_ptr_aligned(&wdata_cur, ggml_row_size(vec_dot_type, ggml_nelements(src1)), sizeof(int64_t)); 1601 } 1602 1603 int64_t * matrix_row_counts = // [n_as] 1604 incr_ptr_aligned(&wdata_cur, n_as*sizeof(int64_t), sizeof(int64_t)); 1605 1606 struct mmid_row_mapping * matrix_rows = // [n_as][ids->ne[0]*ids->ne[1]] 1607 incr_ptr_aligned(&wdata_cur, n_as*ids->ne[0]*ids->ne[1]*sizeof(struct mmid_row_mapping), sizeof(int64_t)); 1608 1609 char (*atomic_current_chunk)[CACHE_LINE_SIZE] = // [n_as] 1610 incr_ptr_aligned(&wdata_cur, CACHE_LINE_SIZE * n_as, CACHE_LINE_SIZE); 1611 1612 // Tiled matmul (see tiled.h); per-thread work buffers, 0 bytes when disabled. The 1613 // reservation is unconditional, the per expert eligibility is decided at dispatch time 1614 char * tiled_scratch = incr_ptr_aligned(&wdata_cur, ggml_tiled_wdata_size(nth, dst), 64); 1615 1616 GGML_ASSERT(params->wsize >= (size_t)((char *) wdata_cur - (char *) params->wdata)); 1617 1618 if (src1->type != vec_dot_type) { 1619 char * wdata = params->wdata; 1620 1621 const size_t nbw0 = ggml_type_size(vec_dot_type); 1622 const size_t nbw1 = ggml_row_size(vec_dot_type, ne10); 1623 const size_t nbw2 = nbw1*ne11; 1624 const size_t nbw3 = nbw2*ne12; 1625 1626 assert(params->wsize >= ne13*nbw3); 1627 GGML_ASSERT(src1->type == GGML_TYPE_F32); 1628 1629 #if 0 1630 for (int64_t i13 = 0; i13 < ne13; ++i13) { 1631 for (int64_t i12 = ith; i12 < ne12; i12 += nth) { 1632 for (int64_t i11 = 0; i11 < ne11; ++i11) { 1633 from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11), 1634 (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1), 1635 ne10); 1636 } 1637 } 1638 } 1639 #else 1640 for (int64_t i13 = 0; i13 < ne13; ++i13) { 1641 for (int64_t i12 = 0; i12 < ne12; ++i12) { 1642 for (int64_t i11 = 0; i11 < ne11; ++i11) { 1643 size_t bs = ggml_blck_size(vec_dot_type); 1644 int64_t ne10_block_start = (ith * ne10/bs) / nth; 1645 int64_t ne10_block_end = ((ith + 1) * ne10/bs) / nth; 1646 from_float((float *)((char *) src1->data + i13*nb13 + i12*nb12 + i11*nb11 + ne10_block_start*bs*nb10), 1647 (void *) (wdata + i13*nbw3 + i12*nbw2 + i11*nbw1 + ne10_block_start*nbw0), 1648 (ne10_block_end - ne10_block_start) * bs); 1649 } 1650 } 1651 } 1652 #endif 1653 } 1654 1655 if (ith == 0) { 1656 // initialize matrix_row_counts 1657 memset(matrix_row_counts, 0, n_as*sizeof(int64_t)); 1658 1659 // group rows by src0 matrix 1660 for (int64_t iid1 = 0; iid1 < ids->ne[1]; ++iid1) { 1661 for (int id = 0; id < n_ids; ++id) { 1662 const int32_t i02 = *(const int32_t *) ((const char *) ids->data + iid1*ids->nb[1] + id*ids->nb[0]); 1663 1664 assert(i02 == -1 || (i02 >= 0 && i02 < n_as)); 1665 1666 if (i02 == -1) { 1667 memset((char *) dst->data + id*nb1 + iid1*nb2, 0, ne0*sizeof(float)); 1668 continue; 1669 } 1670 1671 MMID_MATRIX_ROW(i02, matrix_row_counts[i02]) = (struct mmid_row_mapping) {id, iid1}; 1672 matrix_row_counts[i02] += 1; 1673 } 1674 } 1675 } 1676 1677 // reset current_chunk 1678 for (int cur_a = ith; cur_a < n_as; cur_a += nth) { 1679 atomic_int * current_chunk_ctr = (atomic_int *)(atomic_current_chunk + cur_a); 1680 *current_chunk_ctr = nth; 1681 } 1682 1683 ggml_barrier(params->threadpool); 1684 1685 for (int cur_a = 0; cur_a < n_as; ++cur_a) { 1686 const int64_t cne1 = matrix_row_counts[cur_a]; 1687 1688 if (cne1 == 0) { 1689 continue; 1690 } 1691 1692 // tiled takes over if profitable for this expert (see tiled.h) 1693 if (ggml_compute_forward_mul_mat_id_tiled(params, dst, cur_a, cne1, (const int32_t *) &MMID_MATRIX_ROW(cur_a, 0), tiled_scratch)) { 1694 continue; 1695 } 1696 1697 const char * src0_cur = (const char *) src0->data + cur_a * nb02; 1698 const void * wdata = (src1->type == vec_dot_type) ? src1->data : params->wdata; 1699 const size_t row_size = ggml_row_size(vec_dot_type, ne10); 1700 1701 const int64_t nr0 = ne01; 1702 const int64_t nr1 = cne1; 1703 1704 int chunk_size = 16; 1705 if (nr0 == 1 || nr1 == 1) { 1706 chunk_size = 64; 1707 } 1708 1709 // disable for NUMA 1710 const bool disable_chunking = ggml_is_numa(); 1711 1712 int64_t nchunk0 = (nr0 + chunk_size - 1) / chunk_size; 1713 int64_t nchunk1 = (nr1 + chunk_size - 1) / chunk_size; 1714 1715 if (nchunk0 * nchunk1 < nth * 4 || disable_chunking) { 1716 nchunk0 = nr0 > nr1 ? nth : 1; 1717 nchunk1 = nr0 > nr1 ? 1 : nth; 1718 } 1719 1720 const int64_t dr0 = (nr0 + nchunk0 - 1) / nchunk0; 1721 const int64_t dr1 = (nr1 + nchunk1 - 1) / nchunk1; 1722 1723 int current_chunk = ith; 1724 1725 atomic_int * current_chunk_ctr = (atomic_int *)(atomic_current_chunk + cur_a); 1726 1727 while (current_chunk < nchunk0 * nchunk1) { 1728 const int64_t ith0 = current_chunk % nchunk0; 1729 const int64_t ith1 = current_chunk / nchunk0; 1730 1731 const int64_t ir0_start = dr0 * ith0; 1732 const int64_t ir0_end = MIN(ir0_start + dr0, nr0); 1733 1734 const int64_t ir1_start = dr1 * ith1; 1735 const int64_t ir1_end = MIN(ir1_start + dr1, nr1); 1736 1737 ggml_compute_forward_mul_mat_id_one_chunk( 1738 dst, src0, src1, ids, cur_a, 1739 ir0_start, ir0_end, ir1_start, ir1_end, 1740 src0_cur, matrix_rows, row_size, src1_cont, wdata 1741 ); 1742 1743 if (nth >= nchunk0 * nchunk1) { 1744 break; 1745 } 1746 1747 current_chunk = atomic_fetch_add_explicit(current_chunk_ctr, 1, memory_order_relaxed); 1748 } 1749 } 1750 } 1751 1752 ///////////////////////////////// 1753 1754 static void ggml_compute_forward(struct ggml_compute_params * params, struct ggml_tensor * tensor) { 1755 GGML_ASSERT(params); 1756 1757 if (tensor->op == GGML_OP_NONE || ggml_is_empty(tensor)) { 1758 return; 1759 } 1760 1761 // extra_buffer op? 1762 if (ggml_cpu_extra_compute_forward(params, tensor)) { 1763 return; 1764 } 1765 1766 switch (tensor->op) { 1767 case GGML_OP_DUP: 1768 { 1769 ggml_compute_forward_dup(params, tensor); 1770 } break; 1771 case GGML_OP_ADD: 1772 { 1773 ggml_compute_forward_add(params, tensor); 1774 } break; 1775 case GGML_OP_ADD_ID: 1776 { 1777 ggml_compute_forward_add_id(params, tensor); 1778 } break; 1779 case GGML_OP_ADD1: 1780 { 1781 ggml_compute_forward_add1(params, tensor); 1782 } break; 1783 case GGML_OP_ACC: 1784 { 1785 ggml_compute_forward_acc(params, tensor); 1786 } break; 1787 case GGML_OP_SUB: 1788 { 1789 ggml_compute_forward_sub(params, tensor); 1790 } break; 1791 case GGML_OP_MUL: 1792 { 1793 ggml_compute_forward_mul(params, tensor); 1794 } break; 1795 case GGML_OP_DIV: 1796 { 1797 ggml_compute_forward_div(params, tensor); 1798 } break; 1799 case GGML_OP_SQR: 1800 { 1801 ggml_compute_forward_sqr(params, tensor); 1802 } break; 1803 case GGML_OP_SQRT: 1804 { 1805 ggml_compute_forward_sqrt(params, tensor); 1806 } break; 1807 case GGML_OP_LOG: 1808 { 1809 ggml_compute_forward_log(params, tensor); 1810 } break; 1811 case GGML_OP_SIN: 1812 { 1813 ggml_compute_forward_sin(params, tensor); 1814 } break; 1815 case GGML_OP_COS: 1816 { 1817 ggml_compute_forward_cos(params, tensor); 1818 } break; 1819 case GGML_OP_SUM: 1820 { 1821 ggml_compute_forward_sum(params, tensor); 1822 } break; 1823 case GGML_OP_SUM_ROWS: 1824 { 1825 ggml_compute_forward_sum_rows(params, tensor); 1826 } break; 1827 case GGML_OP_CUMSUM: 1828 { 1829 ggml_compute_forward_cumsum(params, tensor); 1830 } break; 1831 case GGML_OP_MEAN: 1832 { 1833 ggml_compute_forward_mean(params, tensor); 1834 } break; 1835 case GGML_OP_ARGMAX: 1836 { 1837 ggml_compute_forward_argmax(params, tensor); 1838 } break; 1839 case GGML_OP_COUNT_EQUAL: 1840 { 1841 ggml_compute_forward_count_equal(params, tensor); 1842 } break; 1843 case GGML_OP_REPEAT: 1844 { 1845 ggml_compute_forward_repeat(params, tensor); 1846 } break; 1847 case GGML_OP_REPEAT_BACK: 1848 { 1849 ggml_compute_forward_repeat_back(params, tensor); 1850 } break; 1851 case GGML_OP_CONCAT: 1852 { 1853 ggml_compute_forward_concat(params, tensor); 1854 } break; 1855 case GGML_OP_SILU_BACK: 1856 { 1857 ggml_compute_forward_silu_back(params, tensor); 1858 } break; 1859 case GGML_OP_NORM: 1860 { 1861 ggml_compute_forward_norm(params, tensor); 1862 } break; 1863 case GGML_OP_RMS_NORM: 1864 { 1865 ggml_compute_forward_rms_norm(params, tensor); 1866 } break; 1867 case GGML_OP_RMS_NORM_BACK: 1868 { 1869 ggml_compute_forward_rms_norm_back(params, tensor); 1870 } break; 1871 case GGML_OP_GROUP_NORM: 1872 { 1873 ggml_compute_forward_group_norm(params, tensor); 1874 } break; 1875 case GGML_OP_L2_NORM: 1876 { 1877 ggml_compute_forward_l2_norm(params, tensor); 1878 } break; 1879 case GGML_OP_MUL_MAT: 1880 { 1881 ggml_compute_forward_mul_mat(params, tensor); 1882 } break; 1883 case GGML_OP_MUL_MAT_ID: 1884 { 1885 ggml_compute_forward_mul_mat_id(params, tensor); 1886 } break; 1887 case GGML_OP_OUT_PROD: 1888 { 1889 ggml_compute_forward_out_prod(params, tensor); 1890 } break; 1891 case GGML_OP_SCALE: 1892 { 1893 ggml_compute_forward_scale(params, tensor); 1894 } break; 1895 case GGML_OP_SET: 1896 { 1897 ggml_compute_forward_set(params, tensor); 1898 } break; 1899 case GGML_OP_CPY: 1900 { 1901 ggml_compute_forward_cpy(params, tensor); 1902 } break; 1903 case GGML_OP_CONT: 1904 { 1905 ggml_compute_forward_cont(params, tensor); 1906 } break; 1907 case GGML_OP_GET_ROWS: 1908 { 1909 ggml_compute_forward_get_rows(params, tensor); 1910 } break; 1911 case GGML_OP_GET_ROWS_BACK: 1912 { 1913 ggml_compute_forward_get_rows_back(params, tensor); 1914 } break; 1915 case GGML_OP_SET_ROWS: 1916 { 1917 ggml_compute_forward_set_rows(params, tensor); 1918 } break; 1919 case GGML_OP_DIAG: 1920 { 1921 ggml_compute_forward_diag(params, tensor); 1922 } break; 1923 case GGML_OP_DIAG_MASK_INF: 1924 { 1925 ggml_compute_forward_diag_mask_inf(params, tensor); 1926 } break; 1927 case GGML_OP_DIAG_MASK_ZERO: 1928 { 1929 ggml_compute_forward_diag_mask_zero(params, tensor); 1930 } break; 1931 case GGML_OP_SOFT_MAX: 1932 { 1933 ggml_compute_forward_soft_max(params, tensor); 1934 } break; 1935 case GGML_OP_SOFT_MAX_BACK: 1936 { 1937 ggml_compute_forward_soft_max_ext_back(params, tensor); 1938 } break; 1939 case GGML_OP_ROPE: 1940 { 1941 ggml_compute_forward_rope(params, tensor); 1942 } break; 1943 case GGML_OP_ROPE_BACK: 1944 { 1945 ggml_compute_forward_rope_back(params, tensor); 1946 } break; 1947 case GGML_OP_CLAMP: 1948 { 1949 ggml_compute_forward_clamp(params, tensor); 1950 } break; 1951 case GGML_OP_CONV_TRANSPOSE_1D: 1952 { 1953 ggml_compute_forward_conv_transpose_1d(params, tensor); 1954 } break; 1955 case GGML_OP_IM2COL: 1956 { 1957 ggml_compute_forward_im2col(params, tensor); 1958 } break; 1959 case GGML_OP_IM2COL_BACK: 1960 { 1961 ggml_compute_forward_im2col_back_f32(params, tensor); 1962 } break; 1963 case GGML_OP_IM2COL_3D: 1964 { 1965 ggml_compute_forward_im2col_3d(params, tensor); 1966 } break; 1967 case GGML_OP_COL2IM_1D: 1968 { 1969 ggml_compute_forward_col2im_1d(params, tensor); 1970 } break; 1971 case GGML_OP_CONV_2D: 1972 { 1973 ggml_compute_forward_conv_2d(params, tensor); 1974 } break; 1975 case GGML_OP_CONV_3D: 1976 { 1977 ggml_compute_forward_conv_3d(params, tensor); 1978 } break; 1979 case GGML_OP_CONV_2D_DW: 1980 { 1981 ggml_compute_forward_conv_2d_dw(params, tensor); 1982 } break; 1983 case GGML_OP_CONV_TRANSPOSE_2D: 1984 { 1985 ggml_compute_forward_conv_transpose_2d(params, tensor); 1986 } break; 1987 case GGML_OP_POOL_1D: 1988 { 1989 ggml_compute_forward_pool_1d(params, tensor); 1990 } break; 1991 case GGML_OP_POOL_2D: 1992 { 1993 ggml_compute_forward_pool_2d(params, tensor); 1994 } break; 1995 case GGML_OP_POOL_2D_BACK: 1996 { 1997 ggml_compute_forward_pool_2d_back(params, tensor); 1998 } break; 1999 case GGML_OP_UPSCALE: 2000 { 2001 ggml_compute_forward_upscale(params, tensor); 2002 } break; 2003 case GGML_OP_PAD: 2004 { 2005 ggml_compute_forward_pad(params, tensor); 2006 } break; 2007 case GGML_OP_PAD_REFLECT_1D: 2008 { 2009 ggml_compute_forward_pad_reflect_1d(params, tensor); 2010 } break; 2011 case GGML_OP_ROLL: 2012 { 2013 ggml_compute_forward_roll(params, tensor); 2014 } break; 2015 case GGML_OP_ARANGE: 2016 { 2017 ggml_compute_forward_arange(params, tensor); 2018 } break; 2019 case GGML_OP_TIMESTEP_EMBEDDING: 2020 { 2021 ggml_compute_forward_timestep_embedding(params, tensor); 2022 } break; 2023 case GGML_OP_ARGSORT: 2024 { 2025 ggml_compute_forward_argsort(params, tensor); 2026 } break; 2027 case GGML_OP_TOP_K: 2028 { 2029 ggml_compute_forward_top_k(params, tensor); 2030 } break; 2031 case GGML_OP_LEAKY_RELU: 2032 { 2033 ggml_compute_forward_leaky_relu(params, tensor); 2034 } break; 2035 case GGML_OP_TRI: 2036 { 2037 ggml_compute_forward_tri(params, tensor); 2038 } break; 2039 case GGML_OP_FILL: 2040 { 2041 ggml_compute_forward_fill(params, tensor); 2042 } break; 2043 case GGML_OP_FLASH_ATTN_EXT: 2044 { 2045 ggml_compute_forward_flash_attn_ext(params, tensor); 2046 } break; 2047 case GGML_OP_FLASH_ATTN_BACK: 2048 { 2049 int32_t t = ggml_get_op_params_i32(tensor, 0); 2050 GGML_ASSERT(t == 0 || t == 1); 2051 bool masked = t != 0; 2052 ggml_compute_forward_flash_attn_back(params, masked, tensor); 2053 } break; 2054 case GGML_OP_SSM_CONV: 2055 { 2056 ggml_compute_forward_ssm_conv(params, tensor); 2057 } break; 2058 case GGML_OP_SSM_SCAN: 2059 { 2060 ggml_compute_forward_ssm_scan(params, tensor); 2061 } break; 2062 case GGML_OP_WIN_PART: 2063 { 2064 ggml_compute_forward_win_part(params, tensor); 2065 } break; 2066 case GGML_OP_WIN_UNPART: 2067 { 2068 ggml_compute_forward_win_unpart(params, tensor); 2069 } break; 2070 case GGML_OP_UNARY: 2071 { 2072 ggml_compute_forward_unary(params, tensor); 2073 } break; 2074 case GGML_OP_GLU: 2075 { 2076 ggml_compute_forward_glu(params, tensor); 2077 } break; 2078 case GGML_OP_GET_REL_POS: 2079 { 2080 ggml_compute_forward_get_rel_pos(params, tensor); 2081 } break; 2082 case GGML_OP_ADD_REL_POS: 2083 { 2084 ggml_compute_forward_add_rel_pos(params, tensor); 2085 } break; 2086 case GGML_OP_RWKV_WKV6: 2087 { 2088 ggml_compute_forward_rwkv_wkv6(params, tensor); 2089 } break; 2090 case GGML_OP_GATED_LINEAR_ATTN: 2091 { 2092 ggml_compute_forward_gla(params, tensor); 2093 } break; 2094 case GGML_OP_RWKV_WKV7: 2095 { 2096 ggml_compute_forward_rwkv_wkv7(params, tensor); 2097 } break; 2098 case GGML_OP_SOLVE_TRI: 2099 { 2100 ggml_compute_forward_solve_tri(params, tensor); 2101 } break; 2102 case GGML_OP_GATED_DELTA_NET: 2103 { 2104 ggml_compute_forward_gated_delta_net(params, tensor); 2105 } break; 2106 case GGML_OP_LIGHTNING_INDEXER: 2107 { 2108 ggml_compute_forward_lightning_indexer(params, tensor); 2109 } break; 2110 case GGML_OP_DSV4_HC_COMB: 2111 { 2112 ggml_compute_forward_dsv4_hc_comb(params, tensor); 2113 } break; 2114 case GGML_OP_DSV4_HC_PRE: 2115 { 2116 ggml_compute_forward_dsv4_hc_pre(params, tensor); 2117 } break; 2118 case GGML_OP_DSV4_HC_POST: 2119 { 2120 ggml_compute_forward_dsv4_hc_post(params, tensor); 2121 } break; 2122 case GGML_OP_TOP_K_MASK: 2123 { 2124 ggml_compute_forward_top_k_mask(params, tensor); 2125 } break; 2126 case GGML_OP_MAP_CUSTOM1: 2127 { 2128 ggml_compute_forward_map_custom1(params, tensor); 2129 } 2130 break; 2131 case GGML_OP_MAP_CUSTOM2: 2132 { 2133 ggml_compute_forward_map_custom2(params, tensor); 2134 } 2135 break; 2136 case GGML_OP_MAP_CUSTOM3: 2137 { 2138 ggml_compute_forward_map_custom3(params, tensor); 2139 } 2140 break; 2141 case GGML_OP_CUSTOM: 2142 { 2143 ggml_compute_forward_custom(params, tensor); 2144 } 2145 break; 2146 case GGML_OP_CROSS_ENTROPY_LOSS: 2147 { 2148 ggml_compute_forward_cross_entropy_loss(params, tensor); 2149 } 2150 break; 2151 case GGML_OP_CROSS_ENTROPY_LOSS_BACK: 2152 { 2153 ggml_compute_forward_cross_entropy_loss_back(params, tensor); 2154 } 2155 break; 2156 case GGML_OP_OPT_STEP_ADAMW: 2157 { 2158 ggml_compute_forward_opt_step_adamw(params, tensor); 2159 } 2160 break; 2161 case GGML_OP_OPT_STEP_SGD: 2162 { 2163 ggml_compute_forward_opt_step_sgd(params, tensor); 2164 } 2165 break; 2166 case GGML_OP_NONE: 2167 { 2168 // nop 2169 } break; 2170 case GGML_OP_RESHAPE: 2171 { 2172 // nop 2173 } break; 2174 case GGML_OP_PERMUTE: 2175 { 2176 // nop 2177 } break; 2178 case GGML_OP_VIEW: 2179 { 2180 // nop 2181 } break; 2182 case GGML_OP_TRANSPOSE: 2183 { 2184 // nop 2185 } break; 2186 case GGML_OP_COUNT: 2187 { 2188 GGML_ABORT("fatal error"); 2189 } 2190 } 2191 } 2192 2193 // Android's libc implementation "bionic" does not support setting affinity 2194 #if defined(__gnu_linux__) 2195 static void set_numa_thread_affinity(int thread_n) { 2196 if (!ggml_is_numa()) { 2197 return; 2198 } 2199 2200 int node_num; 2201 int rv; 2202 size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus); 2203 2204 switch(g_state.numa.numa_strategy) { 2205 case GGML_NUMA_STRATEGY_DISTRIBUTE: 2206 // run thread on node_num thread_n / (threads per node) 2207 node_num = thread_n % g_state.numa.n_nodes; 2208 break; 2209 case GGML_NUMA_STRATEGY_ISOLATE: 2210 // run thread on current_node 2211 node_num = g_state.numa.current_node; 2212 break; 2213 case GGML_NUMA_STRATEGY_NUMACTL: 2214 // use the cpuset that numactl gave us 2215 rv = pthread_setaffinity_np(pthread_self(), setsize, &g_state.numa.cpuset); 2216 if (rv) { 2217 fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n",strerror(rv)); 2218 } 2219 return; 2220 default: 2221 return; 2222 } 2223 2224 struct ggml_numa_node * node = &g_state.numa.nodes[node_num]; 2225 2226 cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus); 2227 CPU_ZERO_S(setsize, cpus); 2228 for (size_t i = 0; i < node->n_cpus; ++i) { 2229 CPU_SET_S(node->cpus[i], setsize, cpus); 2230 } 2231 2232 rv = pthread_setaffinity_np(pthread_self(), setsize, cpus); 2233 if (rv) { 2234 fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv)); 2235 } 2236 2237 CPU_FREE(cpus); 2238 } 2239 2240 static void clear_numa_thread_affinity(void) { 2241 if (!ggml_is_numa()) { 2242 return; 2243 } 2244 2245 size_t setsize = CPU_ALLOC_SIZE(g_state.numa.total_cpus); 2246 2247 cpu_set_t * cpus = CPU_ALLOC(g_state.numa.total_cpus); 2248 CPU_ZERO_S(setsize, cpus); 2249 for (unsigned i = 0; i < g_state.numa.total_cpus; ++i) { 2250 CPU_SET_S(i, setsize, cpus); 2251 } 2252 2253 int rv = pthread_setaffinity_np(pthread_self(), setsize, cpus); 2254 if (rv) { 2255 fprintf(stderr, "warning: pthread_setaffinity_np() failed: %s\n", strerror(rv)); 2256 } 2257 2258 CPU_FREE(cpus); 2259 } 2260 #else 2261 // TODO: Windows etc. 2262 // (the linux implementation may also work on BSD, someone should test) 2263 static void set_numa_thread_affinity(int thread_n) { UNUSED(thread_n); } 2264 static void clear_numa_thread_affinity(void) {} 2265 #endif 2266 2267 static int ggml_get_n_tasks(struct ggml_tensor * node, int n_threads) { 2268 int n_tasks = 0; 2269 2270 if (ggml_is_empty(node)) { 2271 // no need to multi-thread a no-op 2272 n_tasks = 1; 2273 return n_tasks; 2274 } 2275 2276 switch (node->op) { 2277 case GGML_OP_CPY: 2278 case GGML_OP_DUP: 2279 case GGML_OP_CONT: 2280 case GGML_OP_ADD: 2281 case GGML_OP_ADD_ID: 2282 case GGML_OP_ADD1: 2283 case GGML_OP_ACC: 2284 case GGML_OP_CUMSUM: 2285 case GGML_OP_TRI: 2286 case GGML_OP_FILL: 2287 { 2288 n_tasks = n_threads; 2289 } break; 2290 case GGML_OP_SUB: 2291 case GGML_OP_SQR: 2292 case GGML_OP_SQRT: 2293 case GGML_OP_LOG: 2294 case GGML_OP_SIN: 2295 case GGML_OP_COS: 2296 case GGML_OP_SUM: 2297 case GGML_OP_SUM_ROWS: 2298 case GGML_OP_MEAN: 2299 case GGML_OP_ARGMAX: 2300 { 2301 n_tasks = 1; 2302 } break; 2303 case GGML_OP_COUNT_EQUAL: 2304 case GGML_OP_SOLVE_TRI: 2305 case GGML_OP_GATED_DELTA_NET: 2306 case GGML_OP_DSV4_HC_COMB: 2307 case GGML_OP_DSV4_HC_PRE: 2308 case GGML_OP_DSV4_HC_POST: 2309 case GGML_OP_TOP_K_MASK: 2310 { 2311 n_tasks = n_threads; 2312 } break; 2313 case GGML_OP_REPEAT: 2314 case GGML_OP_REPEAT_BACK: 2315 case GGML_OP_LEAKY_RELU: 2316 { 2317 n_tasks = 1; 2318 } break; 2319 case GGML_OP_UNARY: 2320 switch (ggml_get_unary_op(node)) { 2321 case GGML_UNARY_OP_ABS: 2322 case GGML_UNARY_OP_SGN: 2323 case GGML_UNARY_OP_NEG: 2324 case GGML_UNARY_OP_STEP: 2325 case GGML_UNARY_OP_TANH: 2326 case GGML_UNARY_OP_ELU: 2327 case GGML_UNARY_OP_RELU: 2328 case GGML_UNARY_OP_SIGMOID: 2329 case GGML_UNARY_OP_HARDSWISH: 2330 case GGML_UNARY_OP_HARDSIGMOID: 2331 case GGML_UNARY_OP_EXP: 2332 case GGML_UNARY_OP_SOFTPLUS: 2333 case GGML_UNARY_OP_EXPM1: 2334 case GGML_UNARY_OP_FLOOR: 2335 case GGML_UNARY_OP_CEIL: 2336 case GGML_UNARY_OP_ROUND: 2337 case GGML_UNARY_OP_TRUNC: 2338 { 2339 n_tasks = 1; 2340 } break; 2341 2342 case GGML_UNARY_OP_GELU: 2343 case GGML_UNARY_OP_GELU_ERF: 2344 case GGML_UNARY_OP_GELU_QUICK: 2345 case GGML_UNARY_OP_SILU: 2346 case GGML_UNARY_OP_XIELU: 2347 { 2348 n_tasks = n_threads; 2349 } break; 2350 default: 2351 GGML_ABORT("fatal error"); 2352 } 2353 break; 2354 case GGML_OP_GLU: 2355 switch (ggml_get_glu_op(node)) { 2356 case GGML_GLU_OP_REGLU: 2357 case GGML_GLU_OP_GEGLU: 2358 case GGML_GLU_OP_SWIGLU: 2359 case GGML_GLU_OP_SWIGLU_OAI: 2360 case GGML_GLU_OP_GEGLU_ERF: 2361 case GGML_GLU_OP_GEGLU_QUICK: 2362 case GGML_GLU_OP_SWIGLU_CLAMP: 2363 { 2364 n_tasks = n_threads; 2365 } break; 2366 default: 2367 GGML_ABORT("fatal error"); 2368 } 2369 break; 2370 case GGML_OP_SILU_BACK: 2371 case GGML_OP_MUL: 2372 case GGML_OP_DIV: 2373 case GGML_OP_NORM: 2374 case GGML_OP_RMS_NORM: 2375 case GGML_OP_RMS_NORM_BACK: 2376 case GGML_OP_L2_NORM: 2377 case GGML_OP_GROUP_NORM: 2378 case GGML_OP_CONCAT: 2379 case GGML_OP_MUL_MAT: 2380 case GGML_OP_MUL_MAT_ID: 2381 case GGML_OP_OUT_PROD: 2382 case GGML_OP_SET_ROWS: 2383 { 2384 n_tasks = n_threads; 2385 } break; 2386 case GGML_OP_GET_ROWS: 2387 { 2388 // FIXME: get_rows can use additional threads, but the cost of launching additional threads 2389 // decreases performance with GPU offloading 2390 //n_tasks = n_threads; 2391 n_tasks = 1; 2392 } break; 2393 case GGML_OP_SCALE: 2394 case GGML_OP_SET: 2395 case GGML_OP_RESHAPE: 2396 case GGML_OP_VIEW: 2397 case GGML_OP_PERMUTE: 2398 case GGML_OP_TRANSPOSE: 2399 case GGML_OP_GET_ROWS_BACK: 2400 case GGML_OP_DIAG: 2401 { 2402 n_tasks = 1; 2403 } break; 2404 case GGML_OP_DIAG_MASK_ZERO: 2405 case GGML_OP_DIAG_MASK_INF: 2406 case GGML_OP_SOFT_MAX_BACK: 2407 case GGML_OP_ROPE: 2408 case GGML_OP_ROPE_BACK: 2409 case GGML_OP_ADD_REL_POS: 2410 { 2411 n_tasks = n_threads; 2412 } break; 2413 case GGML_OP_CLAMP: 2414 { 2415 n_tasks = 1; //TODO 2416 } break; 2417 case GGML_OP_SOFT_MAX: 2418 { 2419 n_tasks = MIN(n_threads, ggml_nrows(node->src[0])); 2420 } break; 2421 case GGML_OP_IM2COL: 2422 case GGML_OP_IM2COL_BACK: 2423 case GGML_OP_IM2COL_3D: 2424 case GGML_OP_CONV_2D: 2425 case GGML_OP_CONV_3D: 2426 case GGML_OP_CONV_2D_DW: 2427 case GGML_OP_COL2IM_1D: 2428 case GGML_OP_CONV_TRANSPOSE_1D: 2429 case GGML_OP_CONV_TRANSPOSE_2D: 2430 { 2431 n_tasks = n_threads; 2432 } break; 2433 case GGML_OP_POOL_1D: 2434 case GGML_OP_POOL_2D: 2435 case GGML_OP_POOL_2D_BACK: 2436 { 2437 n_tasks = 1; 2438 } break; 2439 case GGML_OP_UPSCALE: 2440 case GGML_OP_PAD: 2441 case GGML_OP_PAD_REFLECT_1D: 2442 case GGML_OP_ROLL: 2443 case GGML_OP_ARANGE: 2444 case GGML_OP_TIMESTEP_EMBEDDING: 2445 case GGML_OP_ARGSORT: 2446 case GGML_OP_TOP_K: 2447 case GGML_OP_FLASH_ATTN_EXT: 2448 case GGML_OP_FLASH_ATTN_BACK: 2449 case GGML_OP_SSM_CONV: 2450 case GGML_OP_SSM_SCAN: 2451 case GGML_OP_LIGHTNING_INDEXER: 2452 { 2453 n_tasks = n_threads; 2454 } break; 2455 case GGML_OP_RWKV_WKV6: 2456 case GGML_OP_GATED_LINEAR_ATTN: 2457 case GGML_OP_RWKV_WKV7: 2458 { 2459 const int64_t n_heads = node->src[1]->ne[1]; 2460 n_tasks = MIN(n_threads, n_heads); 2461 } break; 2462 case GGML_OP_WIN_PART: 2463 case GGML_OP_WIN_UNPART: 2464 case GGML_OP_GET_REL_POS: 2465 { 2466 n_tasks = 1; 2467 } break; 2468 case GGML_OP_MAP_CUSTOM1: 2469 { 2470 struct ggml_map_custom1_op_params p; 2471 memcpy(&p, node->op_params, sizeof(p)); 2472 if (p.n_tasks == GGML_N_TASKS_MAX) { 2473 n_tasks = n_threads; 2474 } else { 2475 n_tasks = MIN(p.n_tasks, n_threads); 2476 } 2477 } break; 2478 case GGML_OP_MAP_CUSTOM2: 2479 { 2480 struct ggml_map_custom2_op_params p; 2481 memcpy(&p, node->op_params, sizeof(p)); 2482 if (p.n_tasks == GGML_N_TASKS_MAX) { 2483 n_tasks = n_threads; 2484 } else { 2485 n_tasks = MIN(p.n_tasks, n_threads); 2486 } 2487 } break; 2488 case GGML_OP_MAP_CUSTOM3: 2489 { 2490 struct ggml_map_custom3_op_params p; 2491 memcpy(&p, node->op_params, sizeof(p)); 2492 if (p.n_tasks == GGML_N_TASKS_MAX) { 2493 n_tasks = n_threads; 2494 } else { 2495 n_tasks = MIN(p.n_tasks, n_threads); 2496 } 2497 } break; 2498 case GGML_OP_CUSTOM: 2499 { 2500 struct ggml_custom_op_params p; 2501 memcpy(&p, node->op_params, sizeof(p)); 2502 if (p.n_tasks == GGML_N_TASKS_MAX) { 2503 n_tasks = n_threads; 2504 } else { 2505 n_tasks = MIN(p.n_tasks, n_threads); 2506 } 2507 } break; 2508 case GGML_OP_CROSS_ENTROPY_LOSS: 2509 case GGML_OP_CROSS_ENTROPY_LOSS_BACK: 2510 case GGML_OP_OPT_STEP_ADAMW: 2511 case GGML_OP_OPT_STEP_SGD: 2512 { 2513 n_tasks = n_threads; 2514 } break; 2515 case GGML_OP_NONE: 2516 { 2517 n_tasks = 1; 2518 } break; 2519 case GGML_OP_COUNT: 2520 { 2521 GGML_ABORT("fatal error"); 2522 } 2523 default: 2524 { 2525 fprintf(stderr, "%s: op not implemented: ", __func__); 2526 if (node->op < GGML_OP_COUNT) { 2527 fprintf(stderr, "%s\n", ggml_op_name(node->op)); 2528 } else { 2529 fprintf(stderr, "%d\n", node->op); 2530 } 2531 GGML_ABORT("fatal error"); 2532 } 2533 } 2534 2535 assert(n_tasks > 0); 2536 2537 return n_tasks; 2538 } 2539 2540 static thread_ret_t ggml_graph_compute_secondary_thread(void* data); 2541 2542 #if defined(_WIN32) 2543 #include "windows.h" 2544 2545 // TODO: support > 64 CPUs 2546 static bool ggml_thread_apply_affinity(bool * mask) { 2547 HANDLE h = GetCurrentThread(); 2548 uint64_t bitmask = 0ULL; 2549 2550 assert(GGML_MAX_N_THREADS >= 64); 2551 2552 for (int32_t i = 0; i < 8; i++) { 2553 int32_t idx = i * 8; 2554 uint8_t val = 0; 2555 val |= mask[idx + 0] << 0; 2556 val |= mask[idx + 1] << 1; 2557 val |= mask[idx + 2] << 2; 2558 val |= mask[idx + 3] << 3; 2559 val |= mask[idx + 4] << 4; 2560 val |= mask[idx + 5] << 5; 2561 val |= mask[idx + 6] << 6; 2562 val |= mask[idx + 7] << 7; 2563 bitmask |= (uint64_t)val << idx; 2564 } 2565 2566 for (int32_t i = 64; i < GGML_MAX_N_THREADS; i++) { 2567 if (mask[i]) { 2568 fprintf(stderr, "warn: setting thread-affinity for > 64 CPUs isn't supported on windows!\n"); 2569 break; 2570 } 2571 } 2572 2573 DWORD_PTR m = (DWORD_PTR)bitmask; 2574 2575 m = SetThreadAffinityMask(h, m); 2576 2577 return m != 0; 2578 } 2579 2580 static bool ggml_thread_apply_priority(int32_t prio) { 2581 // Note that on Windows the Process Priority Class must be updated in order to set Thread priority. 2582 // This is up to the applications. 2583 DWORD p = THREAD_PRIORITY_NORMAL; 2584 switch (prio) { 2585 case GGML_SCHED_PRIO_LOW: p = THREAD_PRIORITY_BELOW_NORMAL; break; 2586 case GGML_SCHED_PRIO_NORMAL: p = THREAD_PRIORITY_NORMAL; break; 2587 case GGML_SCHED_PRIO_MEDIUM: p = THREAD_PRIORITY_ABOVE_NORMAL; break; 2588 case GGML_SCHED_PRIO_HIGH: p = THREAD_PRIORITY_HIGHEST; break; 2589 case GGML_SCHED_PRIO_REALTIME: p = THREAD_PRIORITY_TIME_CRITICAL; break; 2590 } 2591 2592 if (prio != GGML_SCHED_PRIO_LOW) { 2593 // Tell Windows that this thread should not be throttled (needs its own CPU core). 2594 // Newer Windows 11 versions aggressively park (offline) CPU cores and often place 2595 // all our threads onto the first 4 cores which results in terrible performance with 2596 // n_threads > 4 2597 #if _WIN32_WINNT >= 0x0602 2598 THREAD_POWER_THROTTLING_STATE t; 2599 ZeroMemory(&t, sizeof(t)); 2600 t.Version = THREAD_POWER_THROTTLING_CURRENT_VERSION; 2601 t.ControlMask = THREAD_POWER_THROTTLING_EXECUTION_SPEED; 2602 t.StateMask = 0; 2603 2604 if (!SetThreadInformation(GetCurrentThread(), ThreadPowerThrottling, &t, sizeof(t))) { 2605 GGML_LOG_DEBUG("failed to disable thread power throttling %d : (%d)\n", prio, (int) GetLastError()); 2606 return false; 2607 } 2608 #endif 2609 } 2610 2611 if (prio == GGML_SCHED_PRIO_NORMAL) { 2612 // Keep inherited policy/priority 2613 return true; 2614 } 2615 2616 if (!SetThreadPriority(GetCurrentThread(), p)) { 2617 fprintf(stderr, "warn: failed to set thread priority %d : (%d)\n", prio, (int) GetLastError()); 2618 return false; 2619 } 2620 2621 return true; 2622 } 2623 2624 #elif defined(__APPLE__) 2625 #include 2626 #include 2627 2628 static bool ggml_thread_apply_affinity(const bool * mask) { 2629 // Not supported on Apple platforms 2630 UNUSED(mask); 2631 return true; 2632 } 2633 2634 static bool ggml_thread_apply_priority(int32_t prio) { 2635 struct sched_param p; 2636 int32_t policy = SCHED_OTHER; 2637 switch (prio) { 2638 // TODO: there seems to be no way to set lower prio on Apple platforms 2639 case GGML_SCHED_PRIO_LOW: policy = SCHED_OTHER; p.sched_priority = 0; break; 2640 case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break; 2641 case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break; 2642 case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break; 2643 case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break; 2644 } 2645 2646 if (prio == GGML_SCHED_PRIO_NORMAL) { 2647 // Keep inherited policy/priority 2648 return true; 2649 } 2650 2651 int32_t err = pthread_setschedparam(pthread_self(), policy, &p); 2652 if (err != 0) { 2653 fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err); 2654 return false; 2655 } 2656 2657 return true; 2658 } 2659 2660 #elif defined(__linux__) 2661 // TODO: this may not work on BSD, to be verified 2662 2663 static bool ggml_thread_apply_affinity(const bool * mask) { 2664 cpu_set_t cpuset; 2665 int err; 2666 2667 CPU_ZERO(&cpuset); 2668 2669 for (uint32_t i = 0; i < GGML_MAX_N_THREADS; i++) { 2670 if (mask[i]) { 2671 GGML_PRINT_DEBUG("Thread %lx: adding %d to cpuset\n", pthread_self(), i); 2672 CPU_SET(i, &cpuset); 2673 } 2674 } 2675 2676 #ifdef __ANDROID__ 2677 err = sched_setaffinity(0, sizeof(cpuset), &cpuset); 2678 if (err < 0) { 2679 err = errno; 2680 } 2681 #else 2682 err = pthread_setaffinity_np(pthread_self(), sizeof(cpuset), &cpuset); 2683 #endif 2684 if (err != 0) { 2685 fprintf(stderr, "warn: failed to set affinity mask 0x%llx : %s (%d)\n", (unsigned long long)mask, strerror(err), err); 2686 return false; 2687 } 2688 2689 return true; 2690 } 2691 2692 static bool ggml_thread_apply_priority(int32_t prio) { 2693 struct sched_param p; 2694 int32_t policy = SCHED_OTHER; 2695 switch (prio) { 2696 case GGML_SCHED_PRIO_LOW: policy = SCHED_BATCH; p.sched_priority = 0; break; 2697 case GGML_SCHED_PRIO_NORMAL: policy = SCHED_OTHER; p.sched_priority = 0; break; 2698 case GGML_SCHED_PRIO_MEDIUM: policy = SCHED_FIFO; p.sched_priority = 40; break; 2699 case GGML_SCHED_PRIO_HIGH: policy = SCHED_FIFO; p.sched_priority = 80; break; 2700 case GGML_SCHED_PRIO_REALTIME: policy = SCHED_FIFO; p.sched_priority = 90; break; 2701 } 2702 2703 if (prio == GGML_SCHED_PRIO_NORMAL) { 2704 // Keep inherited policy/priority 2705 return true; 2706 } 2707 2708 int32_t err = pthread_setschedparam(pthread_self(), policy, &p); 2709 if (err != 0) { 2710 fprintf(stderr, "warn: failed to set thread priority %d : %s (%d)\n", prio, strerror(err), err); 2711 return false; 2712 } 2713 2714 return true; 2715 } 2716 2717 #else // unsupported platforms 2718 2719 static bool ggml_thread_apply_affinity(const bool * mask) { 2720 UNUSED(mask); 2721 return true; 2722 } 2723 2724 static bool ggml_thread_apply_priority(int32_t prio) { 2725 UNUSED(prio); 2726 return true; 2727 } 2728 2729 #endif 2730 2731 static bool ggml_thread_cpumask_is_valid(const bool * mask) { 2732 for (int i = 0; i < GGML_MAX_N_THREADS; i++) { 2733 if (mask[i]) { return true; } 2734 } 2735 return false; 2736 } 2737 2738 static void ggml_thread_cpumask_next(const bool * global_mask, bool * local_mask, bool strict, int32_t* iter) { 2739 if (!strict) { 2740 memcpy(local_mask, global_mask, GGML_MAX_N_THREADS); 2741 return; 2742 } else { 2743 memset(local_mask, 0, GGML_MAX_N_THREADS); 2744 int32_t base_idx = *iter; 2745 for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) { 2746 int32_t idx = base_idx + i; 2747 if (idx >= GGML_MAX_N_THREADS) { 2748 // Just a cheaper modulo 2749 idx -= GGML_MAX_N_THREADS; 2750 } 2751 if (global_mask[idx]) { 2752 local_mask[idx] = 1; 2753 *iter = idx + 1; 2754 return; 2755 } 2756 } 2757 } 2758 } 2759 2760 void ggml_threadpool_free(struct ggml_threadpool* threadpool) { 2761 if (!threadpool) return; 2762 2763 const int n_threads = threadpool->n_threads; 2764 2765 #ifndef GGML_USE_OPENMP 2766 struct ggml_compute_state* workers = threadpool->workers; 2767 2768 ggml_mutex_lock(&threadpool->mutex); 2769 2770 threadpool->stop = true; 2771 threadpool->pause = false; 2772 2773 ggml_cond_broadcast(&threadpool->cond); 2774 ggml_mutex_unlock(&threadpool->mutex); 2775 2776 for (int j = 1; j < n_threads; j++) { 2777 int32_t rc = ggml_thread_join(workers[j].thrd, NULL); 2778 GGML_ASSERT(rc == GGML_EXIT_SUCCESS || rc == GGML_EXIT_ABORTED); 2779 UNUSED(rc); 2780 } 2781 2782 ggml_mutex_destroy(&threadpool->mutex); 2783 ggml_cond_destroy(&threadpool->cond); 2784 #endif // GGML_USE_OPENMP 2785 2786 const size_t workers_size = sizeof(struct ggml_compute_state) * n_threads; 2787 ggml_aligned_free(threadpool->workers, workers_size); 2788 ggml_aligned_free(threadpool, sizeof(struct ggml_threadpool)); 2789 } 2790 2791 #ifndef GGML_USE_OPENMP 2792 // pause/resume must be called under mutex 2793 static void ggml_threadpool_pause_locked(struct ggml_threadpool * threadpool) { 2794 GGML_PRINT_DEBUG("Pausing threadpool\n"); 2795 threadpool->pause = true; 2796 ggml_cond_broadcast(&threadpool->cond); 2797 } 2798 2799 static void ggml_threadpool_resume_locked(struct ggml_threadpool * threadpool) { 2800 GGML_PRINT_DEBUG("Resuming threadpool\n"); 2801 threadpool->pause = false; 2802 ggml_cond_broadcast(&threadpool->cond); 2803 } 2804 #endif 2805 2806 void ggml_threadpool_pause(struct ggml_threadpool * threadpool) { 2807 #ifndef GGML_USE_OPENMP 2808 ggml_mutex_lock(&threadpool->mutex); 2809 if (!threadpool->pause) { 2810 ggml_threadpool_pause_locked(threadpool); 2811 } 2812 ggml_mutex_unlock(&threadpool->mutex); 2813 #else 2814 UNUSED(threadpool); 2815 #endif 2816 } 2817 2818 void ggml_threadpool_resume(struct ggml_threadpool * threadpool) { 2819 #ifndef GGML_USE_OPENMP 2820 ggml_mutex_lock(&threadpool->mutex); 2821 if (threadpool->pause) { 2822 ggml_threadpool_resume_locked(threadpool); 2823 } 2824 ggml_mutex_unlock(&threadpool->mutex); 2825 #else 2826 UNUSED(threadpool); 2827 #endif 2828 } 2829 2830 struct ggml_cplan ggml_graph_plan( 2831 const struct ggml_cgraph * cgraph, 2832 int n_threads, 2833 struct ggml_threadpool * threadpool) { 2834 2835 if (threadpool == NULL) { 2836 //GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads); 2837 } 2838 if (n_threads <= 0) { 2839 n_threads = threadpool ? threadpool->n_threads : GGML_DEFAULT_N_THREADS; 2840 } 2841 2842 #if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__) 2843 // Emscripten without pthreads support can only use a single thread 2844 n_threads = 1; 2845 #endif 2846 2847 #if defined(__wasi__) 2848 // WASI doesn't support parallelism yet 2849 n_threads = 1; 2850 #endif 2851 2852 size_t work_size = 0; 2853 2854 struct ggml_cplan cplan; 2855 memset(&cplan, 0, sizeof(struct ggml_cplan)); 2856 2857 int max_tasks = 1; 2858 2859 // thread scheduling for the different operations + work buffer size estimation 2860 for (int i = 0; i < cgraph->n_nodes; i++) { 2861 struct ggml_tensor * node = cgraph->nodes[i]; 2862 2863 const int n_tasks = ggml_get_n_tasks(node, n_threads); 2864 2865 max_tasks = MAX(max_tasks, n_tasks); 2866 2867 size_t cur = 0; 2868 2869 if (!ggml_cpu_extra_work_size(n_threads, node, &cur)) { 2870 switch (node->op) { 2871 case GGML_OP_CPY: 2872 case GGML_OP_DUP: 2873 { 2874 if (ggml_is_quantized(node->type) || 2875 // F16 -> BF16 and BF16 -> F16 copies go through intermediate F32 2876 (node->src[0]->type == GGML_TYPE_F16 && node->src[1] && node->src[1]->type == GGML_TYPE_BF16) || 2877 (node->src[0]->type == GGML_TYPE_BF16 && node->src[1] && node->src[1]->type == GGML_TYPE_F16) || 2878 // conversion between F32 and I32 2879 (node->src[0]->type == GGML_TYPE_F32 && node->src[1] && node->src[1]->type == GGML_TYPE_I32) || 2880 (node->src[0]->type == GGML_TYPE_I32 && node->src[1] && node->src[1]->type == GGML_TYPE_F32)) { 2881 cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks; 2882 } 2883 } break; 2884 case GGML_OP_ADD: 2885 case GGML_OP_ADD_ID: 2886 case GGML_OP_ADD1: 2887 { 2888 if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3) { 2889 cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; 2890 } 2891 } break; 2892 case GGML_OP_ACC: 2893 { 2894 if (ggml_is_quantized(node->src[0]->type)) { 2895 cur = ggml_type_size(GGML_TYPE_F32) * node->src[1]->ne[0] * n_tasks; 2896 } 2897 } break; 2898 case GGML_OP_COUNT_EQUAL: 2899 { 2900 cur = ggml_type_size(node->type)*n_tasks; 2901 } break; 2902 case GGML_OP_MUL_MAT: 2903 { 2904 const enum ggml_type vec_dot_type = type_traits_cpu[node->src[0]->type].vec_dot_type; 2905 if (node->src[1]->type != vec_dot_type) { 2906 cur = ggml_row_size(vec_dot_type, ggml_nelements(node->src[1])); 2907 } 2908 // Workspace for tiled (see tiled.h) 2909 cur = GGML_PAD(cur, 64); 2910 cur += ggml_tiled_wdata_size(n_tasks, node); 2911 } break; 2912 case GGML_OP_MUL_MAT_ID: 2913 { 2914 cur = 0; 2915 const struct ggml_tensor * src0 = node->src[0]; 2916 const struct ggml_tensor * src1 = node->src[1]; 2917 const struct ggml_tensor * ids = node->src[2]; 2918 const enum ggml_type vec_dot_type = type_traits_cpu[src0->type].vec_dot_type; 2919 const int n_as = src0->ne[2]; 2920 // src1 2921 if (src1->type != vec_dot_type) { 2922 cur += ggml_row_size(vec_dot_type, ggml_nelements(src1)) + sizeof(int64_t); 2923 } 2924 // matrix_row_counts 2925 cur += n_as * sizeof(int64_t) + sizeof(int64_t); 2926 // matrix_rows 2927 cur += n_as*ids->ne[0]*ids->ne[1]*sizeof(struct mmid_row_mapping) + sizeof(int64_t); 2928 // atomic_current_chunk 2929 cur += CACHE_LINE_SIZE*n_as + CACHE_LINE_SIZE; 2930 // Workspace for tiled (see tiled.h) 2931 cur = GGML_PAD(cur, 64); 2932 cur += ggml_tiled_wdata_size(n_tasks, node); 2933 } break; 2934 case GGML_OP_OUT_PROD: 2935 { 2936 if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3 || 2937 node->src[0]->type == GGML_TYPE_F16) { 2938 cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; 2939 } 2940 } break; 2941 case GGML_OP_SET_ROWS: 2942 { 2943 if (node->src[0]->type == GGML_TYPE_F16 && node->type != GGML_TYPE_F16) { 2944 cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks; 2945 } 2946 } break; 2947 case GGML_OP_SOFT_MAX: 2948 case GGML_OP_ROPE: 2949 case GGML_OP_ROPE_BACK: 2950 { 2951 cur = ggml_type_size(GGML_TYPE_F32) * node->ne[0] * n_tasks; 2952 } break; 2953 case GGML_OP_CONV_TRANSPOSE_1D: 2954 { 2955 GGML_ASSERT(node->src[0]->ne[3] == 1); 2956 GGML_ASSERT(node->src[1]->ne[2] == 1); 2957 GGML_ASSERT(node->src[1]->ne[3] == 1); 2958 2959 const int64_t ne00 = node->src[0]->ne[0]; // K 2960 const int64_t ne01 = node->src[0]->ne[1]; // Cout 2961 const int64_t ne02 = node->src[0]->ne[2]; // Cin 2962 const int64_t ne10 = node->src[1]->ne[0]; // L 2963 const int64_t ne11 = node->src[1]->ne[1]; // Cin 2964 2965 if ((node->src[0]->type == GGML_TYPE_F16 || 2966 node->src[0]->type == GGML_TYPE_BF16) && 2967 node->src[1]->type == GGML_TYPE_F32) { 2968 cur += sizeof(ggml_fp16_t)*ne00*ne01*ne02; 2969 cur += sizeof(ggml_fp16_t)*ne10*ne11; 2970 } else if (node->src[0]->type == GGML_TYPE_F32 && 2971 node->src[1]->type == GGML_TYPE_F32) { 2972 cur += sizeof(float)*ne00*ne01*ne02; 2973 cur += sizeof(float)*ne10*ne11; 2974 } else { 2975 GGML_ABORT("fatal error"); 2976 } 2977 } break; 2978 case GGML_OP_CONV_2D: 2979 case GGML_OP_CONV_3D: 2980 { 2981 cur = GGML_IM2COL_WORK_SIZE; 2982 } break; 2983 case GGML_OP_CONV_TRANSPOSE_2D: 2984 { 2985 const int64_t ne00 = node->src[0]->ne[0]; // W 2986 const int64_t ne01 = node->src[0]->ne[1]; // H 2987 const int64_t ne02 = node->src[0]->ne[2]; // Channels Out 2988 const int64_t ne03 = node->src[0]->ne[3]; // Channels In 2989 2990 const int64_t ne10 = node->src[1]->ne[0]; // W 2991 const int64_t ne11 = node->src[1]->ne[1]; // H 2992 const int64_t ne12 = node->src[1]->ne[2]; // Channels In 2993 const int64_t ne13 = node->src[1]->ne[3]; // Batch 2994 2995 GGML_ASSERT(node->src[0]->type == GGML_TYPE_F16 || node->src[0]->type == GGML_TYPE_F32); 2996 GGML_ASSERT(node->src[1]->type == GGML_TYPE_F32); 2997 2998 cur += ggml_type_size(node->src[0]->type) * ne00 * ne01 * ne02 * ne03; 2999 cur += ggml_type_size(node->src[0]->type) * ne10 * ne11 * ne12 * ne13; 3000 3001 } break; 3002 case GGML_OP_TOP_K: 3003 { 3004 cur += sizeof(int32_t)*node->src[0]->ne[0]*n_tasks; 3005 } break; 3006 case GGML_OP_FLASH_ATTN_EXT: 3007 { 3008 const int64_t neq2 = node->src[0]->ne[2]; // number of query heads 3009 const int64_t DK = node->src[1]->ne[0]; 3010 const int64_t DV = node->src[2]->ne[0]; 3011 3012 // Tiled flash attention scratch (tile sizes defined in common.h) 3013 // Per-thread: Q_q + KQ + mask + VKQ32 + V32 + K_f32 + padding 3014 size_t prefill = sizeof(float)*(GGML_FA_TILE_Q*DK + 2*GGML_FA_TILE_Q*GGML_FA_TILE_KV + GGML_FA_TILE_Q*DV + GGML_FA_TILE_KV*DV + GGML_FA_TILE_KV*DK)*n_tasks; 3015 3016 // Decode path: n_kv_chunks = n_tasks (one chunk per thread) 3017 // Per-thread: VKQ accmulator (DV), partial M, partial S + intra-thread scratch for V, Q and VKQ 3018 size_t n_chunks = n_tasks; 3019 size_t decode = sizeof(float)*(neq2*n_chunks*(2+DV) + n_tasks*(DK + 2*DV)); 3020 3021 cur += MAX(prefill, decode); 3022 } break; 3023 case GGML_OP_FLASH_ATTN_BACK: 3024 { 3025 const int64_t D = node->src[0]->ne[0]; 3026 const int64_t ne11 = ggml_up(node->src[1]->ne[1], GGML_SOFT_MAX_UNROLL); 3027 const int64_t mxDn = MAX(D, ne11) * 2; // *2 because of S and SM in ggml_compute_forward_flash_attn_back 3028 if (node->src[1]->type == GGML_TYPE_F32) { 3029 cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1) 3030 cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2 3031 } else if (node->src[1]->type == GGML_TYPE_F16) { 3032 cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1) 3033 cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2 3034 } else if (node->src[1]->type == GGML_TYPE_BF16) { 3035 cur = sizeof(float)*mxDn*n_tasks; // TODO: this can become (n_tasks-1) 3036 cur += sizeof(float)*mxDn*n_tasks; // this is overestimated by x2 3037 } 3038 } break; 3039 3040 case GGML_OP_CROSS_ENTROPY_LOSS: 3041 { 3042 cur = ggml_type_size(node->type)*(n_tasks + node->src[0]->ne[0]*n_tasks); 3043 } break; 3044 case GGML_OP_GATED_DELTA_NET: 3045 { 3046 const int64_t S_v = node->src[2]->ne[0]; 3047 const int64_t K = ggml_get_op_params_i32(node, 0); 3048 const int64_t per_thread = S_v + (K > 1 ? S_v * S_v : 0); 3049 cur = per_thread * sizeof(float) * n_tasks; 3050 } break; 3051 case GGML_OP_COUNT: 3052 { 3053 GGML_ABORT("fatal error"); 3054 } 3055 case GGML_OP_LIGHTNING_INDEXER: 3056 { 3057 // temp buffer for dequantizing lightning indexer keys 3058 const int64_t ne10 = node->src[1]->ne[0]; 3059 cur += sizeof(float)*ne10*n_tasks; 3060 } break; 3061 default: 3062 break; 3063 } 3064 } 3065 3066 work_size = MAX(work_size, cur); 3067 } 3068 3069 if (work_size > 0) { 3070 work_size += CACHE_LINE_SIZE*(n_threads); 3071 } 3072 3073 cplan.threadpool = threadpool; 3074 cplan.n_threads = MIN(max_tasks, n_threads); 3075 cplan.work_size = work_size; 3076 cplan.work_data = NULL; 3077 3078 return cplan; 3079 } 3080 3081 3082 // Try to fuse the current node with subsequent nodes for better performance. 3083 // Returns the number of nodes skipped by fusion (>=1), or 0 if no fusion was applied. 3084 static bool ggml_cpu_disable_fusion = false; // initialized once in ggml_cpu_init(), read-only afterwards 3085 3086 static int ggml_cpu_try_fuse_ops( 3087 const struct ggml_cgraph * cgraph, 3088 const int node_n, 3089 const struct ggml_compute_params * params, 3090 const struct ggml_cplan * cplan) { 3091 3092 if (ggml_cpu_disable_fusion || cplan->use_ref) { 3093 return 0; 3094 } 3095 3096 struct ggml_tensor * node = cgraph->nodes[node_n]; 3097 3098 if (node->op == GGML_OP_RMS_NORM) { 3099 // RMS_NORM + MUL fusion 3100 const enum ggml_op fuse_ops[] = { GGML_OP_RMS_NORM, GGML_OP_MUL }; 3101 if (ggml_can_fuse(cgraph, node_n, fuse_ops, 2)) { 3102 struct ggml_tensor * mul_node = cgraph->nodes[node_n + 1]; 3103 const struct ggml_tensor * mul_w = (mul_node->src[0] == node) 3104 ? mul_node->src[1] : mul_node->src[0]; 3105 if (node->src[0]->type == GGML_TYPE_F32 && 3106 mul_node->type == GGML_TYPE_F32 && 3107 mul_w->type == GGML_TYPE_F32 && 3108 mul_w->ne[0] == node->ne[0] && 3109 mul_w->nb[0] == sizeof(float)) { 3110 3111 ggml_compute_forward_rms_norm_mul_fused(params, node, mul_node); 3112 return 1; 3113 } 3114 } 3115 } 3116 3117 return 0; 3118 } 3119 3120 static thread_ret_t ggml_graph_compute_thread(void * data) { 3121 struct ggml_compute_state * state = (struct ggml_compute_state *) data; 3122 struct ggml_threadpool * tp = state->threadpool; 3123 3124 const struct ggml_cgraph * cgraph = tp->cgraph; 3125 const struct ggml_cplan * cplan = tp->cplan; 3126 3127 #ifdef GGML_USE_CPU_RISCV64_SPACEMIT 3128 ggml_backend_cpu_riscv64_spacemit_set_numa_thread_affinity(state->ith); 3129 #else 3130 set_numa_thread_affinity(state->ith); 3131 #endif 3132 3133 struct ggml_compute_params params = { 3134 /*.ith =*/ state->ith, 3135 /*.nth =*/ atomic_load_explicit(&tp->n_graph, memory_order_relaxed) & GGML_THREADPOOL_N_THREADS_MASK, 3136 /*.wsize =*/ cplan->work_size, 3137 /*.wdata =*/ cplan->work_data, 3138 /*.threadpool =*/ tp, 3139 /*.use_ref =*/ cplan->use_ref, 3140 }; 3141 3142 #ifdef GGML_USE_OPENMP 3143 GGML_PRINT_DEBUG("thread #%d compute-start cplan %p\n", state->ith, (const void *)cplan); 3144 #else 3145 GGML_PRINT_DEBUG("thread #%d compute-start cplan %p last-graph %d\n", state->ith, (const void *)cplan, state->last_graph); 3146 #endif 3147 3148 for (int node_n = 0; node_n < cgraph->n_nodes && atomic_load_explicit(&tp->abort, memory_order_relaxed) != node_n; node_n++) { 3149 struct ggml_tensor * node = cgraph->nodes[node_n]; 3150 3151 if (ggml_op_is_empty(node->op)) { 3152 // skip NOPs 3153 continue; 3154 } 3155 3156 if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) { 3157 continue; 3158 } 3159 3160 // TODO: move fused-op detection into ggml_graph_plan so fusion decisions are made once at planning time 3161 // Try fused ops, fall back to normal compute 3162 const int n_fused = ggml_cpu_try_fuse_ops(cgraph, node_n, ¶ms, cplan); 3163 if (n_fused > 0) { 3164 node_n += n_fused; 3165 } else { 3166 ggml_compute_forward(¶ms, node); 3167 } 3168 3169 if (state->ith == 0 && cplan->abort_callback && 3170 cplan->abort_callback(cplan->abort_callback_data)) { 3171 atomic_store_explicit(&tp->abort, node_n + 1, memory_order_relaxed); 3172 tp->ec = GGML_STATUS_ABORTED; 3173 } 3174 3175 if (node_n + 1 < cgraph->n_nodes) { 3176 ggml_barrier(state->threadpool); 3177 } 3178 } 3179 3180 #ifdef GGML_USE_OPENMP 3181 GGML_PRINT_DEBUG("thread #%d compute-done cplan %p\n", state->ith, (const void *)cplan); 3182 #else 3183 GGML_PRINT_DEBUG("thread #%d compute-done cplan %p last-graph %d\n", state->ith, (const void *)cplan, state->last_graph); 3184 #endif 3185 3186 ggml_barrier(state->threadpool); 3187 3188 #ifdef GGML_USE_CPU_RISCV64_SPACEMIT 3189 ggml_backend_cpu_riscv64_spacemit_clear_numa_thread_affinity_threaded(state->ith); 3190 #endif 3191 3192 return 0; 3193 } 3194 3195 #ifndef GGML_USE_OPENMP 3196 3197 // check if thread is ready to proceed (exit from polling or sleeping) 3198 // returns true if loops should exit, sets state->pending to indicate new work 3199 static inline bool ggml_graph_compute_thread_ready(struct ggml_compute_state * state) { 3200 struct ggml_threadpool * threadpool = state->threadpool; 3201 3202 if (state->pending || threadpool->stop || threadpool->pause) { return true; } 3203 3204 // check for new graph/work 3205 int n_graph = atomic_load_explicit(&threadpool->n_graph, memory_order_relaxed); 3206 int n_threads = n_graph & GGML_THREADPOOL_N_THREADS_MASK; 3207 if (n_graph != state->last_graph) { 3208 state->pending = (state->ith < n_threads); 3209 state->last_graph = n_graph; 3210 return true; 3211 } 3212 3213 return false; 3214 } 3215 3216 // sync thread state after polling 3217 static inline void ggml_graph_compute_thread_sync(struct ggml_compute_state * state) { 3218 // TSAN doesn't support standalone fence yet, we use a dummy read-modify-write instead 3219 #ifdef GGML_TSAN_ENABLED 3220 atomic_fetch_add_explicit(&state->threadpool->n_graph, 0, memory_order_seq_cst); 3221 #else 3222 atomic_thread_fence(memory_order_seq_cst); 3223 #endif 3224 UNUSED(state); 3225 } 3226 3227 static inline bool ggml_graph_compute_poll_for_work(struct ggml_compute_state * state) { 3228 struct ggml_threadpool * threadpool = state->threadpool; 3229 3230 // This seems to make 0 ... 100 a decent range for polling level across modern processors. 3231 // Perhaps, we can adjust it dynamically based on load and things. 3232 const uint64_t n_rounds = 1024UL * 128 * threadpool->poll; 3233 3234 for (uint64_t i=0; !ggml_graph_compute_thread_ready(state) && i < n_rounds; i++) { 3235 // No new work. Keep polling. 3236 ggml_thread_cpu_relax(); 3237 } 3238 3239 return state->pending; 3240 } 3241 3242 static inline bool ggml_graph_compute_check_for_work(struct ggml_compute_state * state) { 3243 struct ggml_threadpool * threadpool = state->threadpool; 3244 3245 if (ggml_graph_compute_poll_for_work(state)) { 3246 ggml_graph_compute_thread_sync(state); 3247 return state->pending; 3248 } 3249 3250 ggml_mutex_lock_shared(&threadpool->mutex); 3251 while (!ggml_graph_compute_thread_ready(state)) { 3252 // No new work. Wait for the signal. 3253 GGML_PRINT_DEBUG("thread #%d waiting for work (sleeping)\n", state->ith); 3254 ggml_cond_wait(&threadpool->cond, &threadpool->mutex); 3255 } 3256 ggml_mutex_unlock_shared(&threadpool->mutex); 3257 3258 return state->pending; 3259 } 3260 3261 static thread_ret_t ggml_graph_compute_secondary_thread(void* data) { 3262 struct ggml_compute_state * state = (struct ggml_compute_state *) data; 3263 struct ggml_threadpool * threadpool = state->threadpool; 3264 3265 ggml_thread_apply_priority(threadpool->prio); 3266 if (ggml_thread_cpumask_is_valid(state->cpumask)) { 3267 ggml_thread_apply_affinity(state->cpumask); 3268 } 3269 3270 while (true) { 3271 // Check if we need to sleep 3272 while (threadpool->pause) { 3273 GGML_PRINT_DEBUG("thread #%d inside pause loop\n", state->ith); 3274 ggml_mutex_lock_shared(&threadpool->mutex); 3275 if (threadpool->pause) { 3276 ggml_cond_wait(&threadpool->cond, &threadpool->mutex); 3277 } 3278 GGML_PRINT_DEBUG("thread #%d resuming after wait\n", state->ith); 3279 ggml_mutex_unlock_shared(&threadpool->mutex); 3280 } 3281 3282 // This needs to be checked for after the cond_wait 3283 if (threadpool->stop) break; 3284 3285 // Check if there is new work 3286 // The main thread is the only one that can dispatch new work 3287 3288 ggml_graph_compute_check_for_work(state); 3289 if (state->pending) { 3290 state->pending = false; 3291 ggml_graph_compute_thread(state); 3292 } 3293 } 3294 3295 return (thread_ret_t) 0; 3296 } 3297 3298 // Start processing new graph 3299 static void ggml_graph_compute_kickoff(struct ggml_threadpool * threadpool, int n_threads) 3300 { 3301 // Always take the mutex here because the worker threads are doing hybrid poll/wait 3302 3303 ggml_mutex_lock(&threadpool->mutex); 3304 3305 // Update the number of active threads and the graph count 3306 int n_graph = atomic_load_explicit(&threadpool->n_graph, memory_order_relaxed) >> GGML_THREADPOOL_N_THREADS_BITS; 3307 n_graph = ((n_graph + 1) << GGML_THREADPOOL_N_THREADS_BITS) | (n_threads & GGML_THREADPOOL_N_THREADS_MASK); 3308 3309 GGML_PRINT_DEBUG("compute-kickoff: n_threads %d n_graph %d\n", n_threads, n_graph); 3310 3311 // Indicate the graph is ready to be processed 3312 // We need the full seq-cst fence here because of the polling threads (used in thread_sync) 3313 atomic_store_explicit(&threadpool->n_graph, n_graph, memory_order_seq_cst); 3314 3315 if (threadpool->pause) { 3316 // Update main thread prio and affinity to match the threadpool settings 3317 ggml_thread_apply_priority(threadpool->prio); 3318 if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) { 3319 ggml_thread_apply_affinity(threadpool->workers[0].cpumask); 3320 } 3321 3322 // resume does cond broadcast 3323 ggml_threadpool_resume_locked(threadpool); 3324 } else { 3325 ggml_cond_broadcast(&threadpool->cond); 3326 } 3327 3328 ggml_mutex_unlock(&threadpool->mutex); 3329 } 3330 3331 #endif // GGML_USE_OPENMP 3332 3333 static struct ggml_threadpool * ggml_threadpool_new_impl( 3334 struct ggml_threadpool_params * tpp, 3335 struct ggml_cgraph * cgraph, 3336 struct ggml_cplan * cplan) { 3337 3338 struct ggml_threadpool * threadpool = 3339 ggml_aligned_malloc(sizeof(struct ggml_threadpool)); 3340 { 3341 threadpool->cgraph = cgraph; 3342 threadpool->cplan = cplan; 3343 threadpool->n_graph = 0; 3344 threadpool->n_barrier = 0; 3345 threadpool->n_barrier_passed = 0; 3346 threadpool->current_chunk = 0; 3347 threadpool->stop = false; 3348 threadpool->pause = tpp->paused; 3349 threadpool->abort = -1; 3350 threadpool->workers = NULL; 3351 threadpool->n_threads = tpp->n_threads; 3352 threadpool->poll = tpp->poll; 3353 threadpool->prio = tpp->prio; 3354 threadpool->ec = GGML_STATUS_SUCCESS; 3355 } 3356 3357 // Allocate and init workers state 3358 const size_t workers_size = sizeof(struct ggml_compute_state) * tpp->n_threads; 3359 struct ggml_compute_state * workers = ggml_aligned_malloc(workers_size); 3360 3361 memset(workers, 0, workers_size); 3362 for (int j = 0; j < tpp->n_threads; j++) { 3363 workers[j].threadpool = threadpool; 3364 workers[j].ith = j; 3365 } 3366 3367 threadpool->workers = workers; 3368 3369 #ifdef GGML_USE_OPENMP 3370 int32_t cpumask_iter = 0; 3371 3372 // Compute CPU masks for each thread 3373 for (int j = 0; j < tpp->n_threads; j++) { 3374 ggml_thread_cpumask_next(tpp->cpumask, workers[j].cpumask, tpp->strict_cpu, &cpumask_iter); 3375 } 3376 #else // GGML_USE_OPENMP 3377 ggml_mutex_init(&threadpool->mutex); 3378 ggml_cond_init(&threadpool->cond); 3379 3380 // Spin the threads for all workers, and update CPU placements. 3381 // Place the main thread last (towards the higher numbered CPU cores). 3382 3383 int32_t cpumask_iter = 0; 3384 3385 for (int j = 1; j < tpp->n_threads; j++) { 3386 ggml_thread_cpumask_next(tpp->cpumask, workers[j].cpumask, tpp->strict_cpu, &cpumask_iter); 3387 3388 int32_t rc = ggml_thread_create(&workers[j].thrd, NULL, ggml_graph_compute_secondary_thread, &workers[j]); 3389 GGML_ASSERT(rc == 0); 3390 } 3391 3392 ggml_thread_cpumask_next(tpp->cpumask, workers[0].cpumask, tpp->strict_cpu, &cpumask_iter); 3393 3394 if (!threadpool->pause) { 3395 // Update main thread prio and affinity at the start, otherwise we'll do it in resume 3396 ggml_thread_apply_priority(threadpool->prio); 3397 if (ggml_thread_cpumask_is_valid(threadpool->workers[0].cpumask)) { 3398 ggml_thread_apply_affinity(threadpool->workers[0].cpumask); 3399 } 3400 } 3401 #endif // GGML_USE_OPENMP 3402 3403 return threadpool; 3404 } 3405 3406 struct ggml_threadpool * ggml_threadpool_new(struct ggml_threadpool_params * tpp) { 3407 return ggml_threadpool_new_impl(tpp, NULL, NULL); 3408 } 3409 3410 enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan) { 3411 ggml_cpu_init(); 3412 3413 GGML_ASSERT(cplan); 3414 GGML_ASSERT(cplan->n_threads > 0); 3415 GGML_ASSERT(cplan->work_size == 0 || cplan->work_data != NULL); 3416 3417 int n_threads = cplan->n_threads; 3418 struct ggml_threadpool * threadpool = cplan->threadpool; 3419 3420 bool disposable_threadpool = false; 3421 3422 if (threadpool == NULL) { 3423 //GGML_PRINT_DEBUG("Threadpool is not specified. Will create a disposable threadpool : n_threads %d\n", n_threads); 3424 disposable_threadpool = true; 3425 3426 struct ggml_threadpool_params ttp = ggml_threadpool_params_default(n_threads); 3427 threadpool = ggml_threadpool_new_impl(&ttp, cgraph, cplan); 3428 } else { 3429 // Reset some of the parameters that need resetting 3430 // No worker threads should be accessing the parameters below at this stage 3431 threadpool->cgraph = cgraph; 3432 threadpool->cplan = cplan; 3433 threadpool->current_chunk = 0; 3434 threadpool->abort = -1; 3435 threadpool->ec = GGML_STATUS_SUCCESS; 3436 } 3437 3438 #ifdef GGML_USE_OPENMP 3439 if (n_threads > 1) { 3440 #pragma omp parallel num_threads(n_threads) 3441 { 3442 #pragma omp single 3443 { 3444 // update the number of threads from the actual number of threads that we got from OpenMP 3445 n_threads = omp_get_num_threads(); 3446 atomic_store_explicit(&threadpool->n_graph, n_threads, memory_order_relaxed); 3447 } 3448 3449 // Apply thread CPU mask and priority 3450 int ith = omp_get_thread_num(); 3451 3452 ggml_thread_apply_priority(threadpool->prio); 3453 if (ggml_thread_cpumask_is_valid(threadpool->workers[ith].cpumask)) { 3454 ggml_thread_apply_affinity(threadpool->workers[ith].cpumask); 3455 } 3456 ggml_graph_compute_thread(&threadpool->workers[ith]); 3457 } 3458 } else { 3459 atomic_store_explicit(&threadpool->n_graph, 1, memory_order_relaxed); 3460 ggml_graph_compute_thread(&threadpool->workers[0]); 3461 } 3462 #else 3463 if (n_threads > threadpool->n_threads) { 3464 GGML_LOG_WARN("cplan requested more threads (%d) than available (%d)\n", n_threads, threadpool->n_threads); 3465 n_threads = threadpool->n_threads; 3466 } 3467 3468 // Kick all threads to start the new graph 3469 ggml_graph_compute_kickoff(threadpool, n_threads); 3470 3471 // This is a work thread too 3472 ggml_graph_compute_thread(&threadpool->workers[0]); 3473 #endif 3474 3475 // don't leave affinity set on the main thread 3476 clear_numa_thread_affinity(); 3477 3478 enum ggml_status ret = threadpool->ec; 3479 3480 if (disposable_threadpool) { 3481 ggml_threadpool_free(threadpool); 3482 } 3483 3484 return ret; 3485 } 3486 3487 enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads) { 3488 struct ggml_cplan cplan = ggml_graph_plan(cgraph, n_threads, NULL); 3489 3490 cplan.work_data = (uint8_t *)ggml_new_buffer(ctx, cplan.work_size); 3491 3492 return ggml_graph_compute(cgraph, &cplan); 3493 } 3494 3495 void ggml_cpu_fp32_to_fp32(const float * x, float * y, int64_t n) { 3496 memcpy(y, x, n * sizeof(float)); 3497 } 3498 3499 void ggml_cpu_fp32_to_fp16(const float * x, ggml_fp16_t * y, int64_t n) { 3500 int64_t i = 0; 3501 #if defined(__F16C__) 3502 #if defined(__AVX512F__) 3503 for (; i + 15 < n; i += 16) { 3504 __m512 x_vec = _mm512_loadu_ps(x + i); 3505 __m256i y_vec = _mm512_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT); 3506 _mm256_storeu_si256((__m256i *)(y + i), y_vec); 3507 } 3508 #endif 3509 for (; i + 7 < n; i += 8) { 3510 __m256 x_vec = _mm256_loadu_ps(x + i); 3511 __m128i y_vec = _mm256_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT); 3512 _mm_storeu_si128((__m128i *)(y + i), y_vec); 3513 } 3514 for (; i + 3 < n; i += 4) { 3515 __m128 x_vec = _mm_loadu_ps(x + i); 3516 __m128i y_vec = _mm_cvtps_ph(x_vec, _MM_FROUND_TO_NEAREST_INT); 3517 _mm_storel_epi64((__m128i *)(y + i), y_vec); 3518 } 3519 #elif defined(__riscv_zvfh) 3520 for (int vl; i < n; i += vl) { 3521 vl = __riscv_vsetvl_e32m2(n - i); 3522 vfloat32m2_t vx = __riscv_vle32_v_f32m2(&x[i], vl); 3523 vfloat16m1_t vy = __riscv_vfncvt_f_f_w_f16m1(vx, vl); 3524 __riscv_vse16_v_f16m1((_Float16 *)&y[i], vy, vl); 3525 } 3526 #elif defined(__VXE__) || defined(__VXE2__) 3527 for (; i + 7 < n; i += 8) { 3528 const uint32x4_t v_yl = __lzs_f32cx4_to_f16(vec_xl(0, x + i + 0)); 3529 const uint32x4_t v_yh = __lzs_f32cx4_to_f16(vec_xl(0, x + i + 4)); 3530 vec_xst(vec_pack(v_yl, v_yh), 0, (uint16_t *)(y + i)); 3531 } 3532 #endif 3533 for (; i < n; ++i) { 3534 y[i] = GGML_CPU_FP32_TO_FP16(x[i]); 3535 } 3536 } 3537 3538 void ggml_cpu_fp16_to_fp32(const ggml_fp16_t * x, float * y, int64_t n) { 3539 int64_t i = 0; 3540 #if defined(__F16C__) 3541 #if defined(__AVX512F__) 3542 for (; i + 15 < n; i += 16) { 3543 __m256i x_vec = _mm256_loadu_si256((const __m256i *)(x + i)); 3544 __m512 y_vec = _mm512_cvtph_ps(x_vec); 3545 _mm512_storeu_ps(y + i, y_vec); 3546 } 3547 #endif 3548 for (; i + 7 < n; i += 8) { 3549 __m128i x_vec = _mm_loadu_si128((const __m128i *)(x + i)); 3550 __m256 y_vec = _mm256_cvtph_ps(x_vec); 3551 _mm256_storeu_ps(y + i, y_vec); 3552 } 3553 for (; i + 3 < n; i += 4) { 3554 __m128i x_vec = _mm_loadl_epi64((const __m128i *)(x + i)); 3555 __m128 y_vec = _mm_cvtph_ps(x_vec); 3556 _mm_storeu_ps(y + i, y_vec); 3557 } 3558 3559 #elif defined(__riscv_v) && defined(__riscv_zvfhmin) 3560 // calculate step size 3561 const int epr = __riscv_vsetvlmax_e16m2(); 3562 const int step = epr * 2; 3563 const int np = (n & ~(step - 1)); 3564 3565 // unroll by 2 3566 for (; i < np; i += step) { 3567 vfloat16m2_t ax0 = __riscv_vle16_v_f16m2((const _Float16*)x + i, epr); 3568 vfloat32m4_t ay0 = __riscv_vfwcvt_f_f_v_f32m4(ax0, epr); 3569 __riscv_vse32_v_f32m4(y + i, ay0, epr); 3570 3571 vfloat16m2_t ax1 = __riscv_vle16_v_f16m2((const _Float16*)x + i + epr, epr); 3572 vfloat32m4_t ay1 = __riscv_vfwcvt_f_f_v_f32m4(ax1, epr); 3573 __riscv_vse32_v_f32m4(y + i + epr, ay1, epr); 3574 } 3575 3576 // leftovers 3577 int vl; 3578 for (i = np; i < n; i += vl) { 3579 vl = __riscv_vsetvl_e16m2(n - i); 3580 vfloat16m2_t ax0 = __riscv_vle16_v_f16m2((const _Float16*)x + i, vl); 3581 vfloat32m4_t ay0 = __riscv_vfwcvt_f_f_v_f32m4(ax0, vl); 3582 __riscv_vse32_v_f32m4(y + i, ay0, vl); 3583 } 3584 3585 #endif 3586 3587 for (; i < n; ++i) { 3588 y[i] = GGML_CPU_FP16_TO_FP32(x[i]); 3589 } 3590 } 3591 3592 void ggml_cpu_fp32_to_bf16(const float * x, ggml_bf16_t * y, int64_t n) { 3593 int64_t i = 0; 3594 for (; i < n; ++i) { 3595 y[i] = GGML_FP32_TO_BF16(x[i]); 3596 } 3597 } 3598 3599 void ggml_cpu_fp32_to_i32(const float * x, int32_t * y, int64_t n) { 3600 int64_t i = 0; 3601 for (; i < n; ++i) { 3602 y[i] = x[i]; 3603 } 3604 } 3605 3606 void ggml_cpu_bf16_to_fp32(const ggml_bf16_t * x, float * y, int64_t n) { 3607 int64_t i = 0; 3608 #if defined(__AVX2__) 3609 #if defined(__AVX512F__) 3610 for (; i + 15 < n; i += 16) { 3611 _mm512_storeu_ps(y + i, 3612 _mm512_castsi512_ps( 3613 _mm512_slli_epi32( 3614 _mm512_cvtepu16_epi32( 3615 _mm256_loadu_si256( 3616 (const __m256i *)(x + i))), 3617 16))); 3618 } 3619 #endif 3620 for (; i + 7 < n; i += 8) { 3621 _mm256_storeu_ps(y + i, 3622 _mm256_castsi256_ps( 3623 _mm256_slli_epi32( 3624 _mm256_cvtepu16_epi32( 3625 _mm_loadu_si128( 3626 (const __m128i *)(x + i))), 3627 16))); 3628 } 3629 #elif defined(__riscv_v) && defined(__riscv_zvfbfmin) 3630 // calculate step size 3631 const int epr = __riscv_vsetvlmax_e16m2(); 3632 const int step = epr * 2; 3633 const int np = (n & ~(step - 1)); 3634 3635 // unroll by 2 3636 for (; i < np; i += step) { 3637 vbfloat16m2_t ax0 = __riscv_vle16_v_bf16m2((const __bf16*)x + i, epr); 3638 vfloat32m4_t ay0 = __riscv_vfwcvtbf16_f_f_v_f32m4(ax0, epr); 3639 __riscv_vse32_v_f32m4(y + i, ay0, epr); 3640 3641 vbfloat16m2_t ax1 = __riscv_vle16_v_bf16m2((const __bf16*)x + i + epr, epr); 3642 vfloat32m4_t ay1 = __riscv_vfwcvtbf16_f_f_v_f32m4(ax1, epr); 3643 __riscv_vse32_v_f32m4(y + i + epr, ay1, epr); 3644 } 3645 3646 // leftovers 3647 int vl; 3648 for (i = np; i < n; i += vl) { 3649 vl = __riscv_vsetvl_e16m2(n - i); 3650 vbfloat16m2_t ax0 = __riscv_vle16_v_bf16m2((const __bf16*)x + i, vl); 3651 vfloat32m4_t ay0 = __riscv_vfwcvtbf16_f_f_v_f32m4(ax0, vl); 3652 __riscv_vse32_v_f32m4(y + i, ay0, vl); 3653 } 3654 #endif 3655 for (; i < n; i++) { 3656 y[i] = GGML_BF16_TO_FP32(x[i]); 3657 } 3658 } 3659 3660 int ggml_cpu_has_avx(void) { 3661 #if defined(__AVX__) 3662 return 1; 3663 #else 3664 return 0; 3665 #endif 3666 } 3667 3668 int ggml_cpu_has_avx_vnni(void) { 3669 #if defined(__AVXVNNI__) 3670 return 1; 3671 #else 3672 return 0; 3673 #endif 3674 } 3675 3676 int ggml_cpu_has_avx2(void) { 3677 #if defined(__AVX2__) 3678 return 1; 3679 #else 3680 return 0; 3681 #endif 3682 } 3683 3684 int ggml_cpu_has_avx512(void) { 3685 #if defined(__AVX512F__) 3686 return 1; 3687 #else 3688 return 0; 3689 #endif 3690 } 3691 3692 int ggml_cpu_has_avx512_vbmi(void) { 3693 #if defined(__AVX512VBMI__) 3694 return 1; 3695 #else 3696 return 0; 3697 #endif 3698 } 3699 3700 int ggml_cpu_has_avx512_vnni(void) { 3701 #if defined(__AVX512VNNI__) 3702 return 1; 3703 #else 3704 return 0; 3705 #endif 3706 } 3707 3708 int ggml_cpu_has_avx512_bf16(void) { 3709 #if defined(__AVX512BF16__) 3710 return 1; 3711 #else 3712 return 0; 3713 #endif 3714 } 3715 3716 int ggml_cpu_has_amx_int8(void) { 3717 #if defined(__AMX_INT8__) 3718 return 1; 3719 #else 3720 return 0; 3721 #endif 3722 } 3723 3724 int ggml_cpu_has_bmi2(void) { 3725 #if defined(__BMI2__) 3726 return 1; 3727 #else 3728 return 0; 3729 #endif 3730 } 3731 3732 int ggml_cpu_has_fma(void) { 3733 #if defined(__FMA__) 3734 return 1; 3735 #else 3736 return 0; 3737 #endif 3738 } 3739 3740 int ggml_cpu_has_arm_fma(void) { 3741 #if defined(__ARM_FEATURE_FMA) 3742 return 1; 3743 #else 3744 return 0; 3745 #endif 3746 } 3747 3748 int ggml_cpu_has_riscv_v(void) { 3749 #if defined(__riscv_v) 3750 return 1; 3751 #else 3752 return 0; 3753 #endif 3754 } 3755 3756 int ggml_cpu_get_rvv_vlen(void) { 3757 #if defined(__riscv) && defined(__riscv_v) 3758 return ggml_riscv_arch_features.rvv_vlen; 3759 #else 3760 return 0; 3761 #endif 3762 } 3763 3764 int ggml_cpu_has_f16c(void) { 3765 #if defined(__F16C__) 3766 return 1; 3767 #else 3768 return 0; 3769 #endif 3770 } 3771 3772 int ggml_cpu_has_fp16_va(void) { 3773 #if defined(__ARM_FEATURE_FP16_VECTOR_ARITHMETIC) 3774 return 1; 3775 #else 3776 return 0; 3777 #endif 3778 } 3779 3780 int ggml_cpu_has_wasm_simd(void) { 3781 #if defined(__wasm_simd128__) 3782 return 1; 3783 #else 3784 return 0; 3785 #endif 3786 } 3787 3788 int ggml_cpu_has_llamafile(void) { 3789 #if defined(GGML_USE_LLAMAFILE) 3790 return 1; 3791 #else 3792 return 0; 3793 #endif 3794 } 3795 3796 int ggml_cpu_has_sse3(void) { 3797 #if defined(__SSE3__) 3798 return 1; 3799 #else 3800 return 0; 3801 #endif 3802 } 3803 3804 int ggml_cpu_has_ssse3(void) { 3805 #if defined(__SSSE3__) 3806 return 1; 3807 #else 3808 return 0; 3809 #endif 3810 } 3811 3812 int ggml_cpu_has_vsx(void) { 3813 #if defined(__POWER9_VECTOR__) 3814 return 1; 3815 #else 3816 return 0; 3817 #endif 3818 } 3819 3820 int ggml_cpu_has_vxe(void) { 3821 #if defined(__VXE__) || defined(__VXE2__) 3822 return 1; 3823 #else 3824 return 0; 3825 #endif 3826 } 3827 3828 int ggml_cpu_has_neon(void) { 3829 #if defined(__ARM_ARCH) && defined(__ARM_NEON) 3830 return 1; 3831 #else 3832 return 0; 3833 #endif 3834 } 3835 3836 int ggml_cpu_has_dotprod(void) { 3837 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_DOTPROD) 3838 return 1; 3839 #else 3840 return 0; 3841 #endif 3842 } 3843 3844 int ggml_cpu_has_sve(void) { 3845 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SVE) 3846 return 1; 3847 #else 3848 return 0; 3849 #endif 3850 } 3851 3852 int ggml_cpu_has_matmul_int8(void) { 3853 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_MATMUL_INT8) 3854 return 1; 3855 #else 3856 return 0; 3857 #endif 3858 } 3859 3860 int ggml_cpu_get_sve_cnt(void) { 3861 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SVE) 3862 return ggml_arm_arch_features.sve_cnt; 3863 #else 3864 return 0; 3865 #endif 3866 } 3867 3868 int ggml_cpu_has_sme(void) { 3869 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SME) 3870 return 1; 3871 #else 3872 return 0; 3873 #endif 3874 } 3875 3876 int ggml_cpu_has_sme2(void) { 3877 #if defined(__ARM_ARCH) && defined(__ARM_FEATURE_SME2) 3878 return 1; 3879 #else 3880 return 0; 3881 #endif 3882 } 3883 3884 void ggml_cpu_init(void) { 3885 // needed to initialize ggml_time 3886 { 3887 struct ggml_init_params params = { 0, NULL, false }; 3888 struct ggml_context * ctx = ggml_init(params); 3889 ggml_free(ctx); 3890 } 3891 3892 ggml_critical_section_start(); 3893 3894 static bool is_first_call = true; 3895 3896 if (is_first_call) { 3897 // initialize GELU, Quick GELU, SILU and EXP F32 tables 3898 { 3899 const uint64_t t_start = ggml_time_us(); UNUSED(t_start); 3900 3901 for (int i = 0; i < (1 << 16); ++i) { 3902 union { 3903 uint16_t u16; 3904 ggml_fp16_t fp16; 3905 } u = {i}; 3906 float f = GGML_COMPUTE_FP16_TO_FP32(u.fp16); 3907 ggml_table_f32_f16[i] = f; 3908 ggml_table_gelu_f16[i] = GGML_CPU_FP32_TO_FP16(ggml_gelu_f32(f)); 3909 ggml_table_gelu_quick_f16[i] = GGML_CPU_FP32_TO_FP16(ggml_gelu_quick_f32(f)); 3910 } 3911 3912 // initialize E8M0 half table (256 entries) 3913 for (int i = 0; i < (1 << 8); ++i) { 3914 ggml_table_f32_e8m0_half[i] = GGML_E8M0_TO_FP32_HALF(i); 3915 } 3916 3917 // initialize UE4M3 table (256 entries) 3918 for (int i = 0; i < (1 << 8); ++i) { 3919 ggml_table_f32_ue4m3[i] = ggml_ue4m3_to_fp32(i); 3920 ggml_table_f32_f8_e4m3[i] = ggml_f8_e4m3_to_fp32(i); 3921 } 3922 3923 const uint64_t t_end = ggml_time_us(); UNUSED(t_end); 3924 3925 GGML_PRINT_DEBUG("%s: GELU, Quick GELU, SILU and EXP tables initialized in %f ms\n", __func__, (t_end - t_start)/1000.0); 3926 3927 #ifdef GGML_USE_OPENMP 3928 //if (!getenv("OMP_WAIT_POLICY")) { 3929 // // set the wait policy to active, so that OpenMP threads don't sleep 3930 // setenv("OMP_WAIT_POLICY", "active", 0) 3931 //} 3932 3933 if (!getenv("KMP_BLOCKTIME")) { 3934 // set the time to wait before sleeping a thread 3935 // this is less aggressive than setting the wait policy to active, but should achieve similar results in most cases 3936 #ifdef _WIN32 3937 _putenv_s("KMP_BLOCKTIME", "200"); // 200ms 3938 #else 3939 setenv("KMP_BLOCKTIME", "200", 0); // 200ms 3940 #endif 3941 } 3942 #endif 3943 } 3944 3945 #if defined(__ARM_ARCH) 3946 ggml_init_arm_arch_features(); 3947 #endif 3948 3949 #if defined(__riscv) 3950 ggml_init_riscv_arch_features(); 3951 #endif 3952 3953 { 3954 const char * env = getenv("GGML_CPU_DISABLE_FUSION"); 3955 ggml_cpu_disable_fusion = (env != NULL && atoi(env) == 1); 3956 } 3957 3958 is_first_call = false; 3959 } 3960 3961 ggml_critical_section_end(); 3962 }