Coverage Report

Created: 2026-02-26 07:06

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