okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1a (451f3e8a6): own-stack phase 1A and cleanup 5.4; the ggml/MMQ sources the engines build are vendored in third_party/strata-ggml (frozen at the pin, manifest and check), default engine builds need no llama.cpp download, the TQ overlay is plain files, CMakeLists.txt is split into cmake/backends/*; every engine unchanged (CUDA/HIP gfx1201/gfx1151/SYCL device code identical, SYCL 22/22 checksums, Metal 104/105 objects with only __TIME__ differing, CUDA tokens 26/26); release scripts still pass -DSTRATA_GGML_DIR (owner go 11-08)508e6999a

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