Debian Codegraph @

external/whispercpp/ggml-cpu.cpp

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