Coverage Report

Created: 2026-02-01 07:21

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