Coverage Report

Created: 2026-07-16 06:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/ggml/src/ggml.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.h"
5
#include "ggml-impl.h"
6
#include "ggml-threading.h"
7
#include "ggml-cpu.h"
8
#include "ggml.h"
9
10
// FIXME: required here for quantization functions
11
#include "ggml-quants.h"
12
13
#ifdef GGML_USE_CPU_HBM
14
#include <hbwmalloc.h>
15
#endif
16
17
#if defined(_MSC_VER) || defined(__MINGW32__)
18
#include <malloc.h> // using malloc.h with MSC/MINGW
19
#elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
20
#include <alloca.h>
21
#endif
22
23
#include <assert.h>
24
#include <errno.h>
25
#include <time.h>
26
#include <math.h>
27
#include <stdlib.h>
28
#include <string.h>
29
#include <stdint.h>
30
#include <inttypes.h>
31
#include <stdio.h>
32
#include <float.h>
33
#include <limits.h>
34
#include <stdarg.h>
35
#include <signal.h>
36
#if defined(__gnu_linux__)
37
#include <syscall.h>
38
#endif
39
40
#if defined(__APPLE__)
41
#include <unistd.h>
42
#include <mach/mach.h>
43
#include <TargetConditionals.h>
44
#endif
45
46
#if defined(_WIN32)
47
#define WIN32_LEAN_AND_MEAN
48
#ifndef NOMINMAX
49
    #define NOMINMAX
50
#endif
51
#include <windows.h>
52
#endif
53
54
0
#define UNUSED GGML_UNUSED
55
56
0
uint64_t ggml_graph_next_uid(void) {
57
#ifdef _MSC_VER
58
#if defined(_WIN32)
59
    static volatile LONG counter = 1;
60
    return (uint64_t) InterlockedIncrement(&counter) - 1;
61
#else
62
    static volatile long long counter = 1;
63
    return (uint64_t) _InterlockedIncrement64(&counter) - 1;
64
#endif
65
#else
66
0
    static uint64_t counter = 1;
67
0
    return __atomic_fetch_add(&counter, 1, __ATOMIC_RELAXED);
68
0
#endif
69
0
}
70
71
// Needed for ggml_fp32_to_bf16_row()
72
#if defined(__AVX512BF16__)
73
#if defined(_MSC_VER)
74
#define m512i(p) p
75
#else
76
#include <immintrin.h>
77
#define m512i(p) (__m512i)(p)
78
#endif // defined(_MSC_VER)
79
#endif // defined(__AVX512BF16__)
80
81
#if defined(__linux__) || \
82
    defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
83
    (defined(__APPLE__) && !TARGET_OS_TV && !TARGET_OS_WATCH)
84
85
#include <unistd.h>
86
#include <sys/types.h>
87
#include <sys/stat.h>
88
#include <sys/wait.h>
89
#if defined(__linux__)
90
#include <sys/prctl.h>
91
#endif
92
93
#if defined(__ANDROID__)
94
#include <unwind.h>
95
#include <dlfcn.h>
96
#include <stdio.h>
97
98
struct backtrace_state {
99
    void ** current;
100
    void ** end;
101
};
102
103
static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context* context, void* arg) {
104
    struct backtrace_state * state = (struct backtrace_state *)arg;
105
    uintptr_t pc = _Unwind_GetIP(context);
106
    if (pc) {
107
        if (state->current == state->end) {
108
            return _URC_END_OF_STACK;
109
        } else {
110
            *state->current++ = (void*)pc;
111
        }
112
    }
113
    return _URC_NO_REASON;
114
}
115
116
static void ggml_print_backtrace_symbols(void) {
117
    const int max = 100;
118
    void* buffer[max];
119
120
    struct backtrace_state state = {buffer, buffer + max};
121
    _Unwind_Backtrace(unwind_callback, &state);
122
123
    int count = state.current - buffer;
124
125
    for (int idx = 0; idx < count; ++idx) {
126
        const void * addr = buffer[idx];
127
        const char * symbol = "";
128
129
        Dl_info info;
130
        if (dladdr(addr, &info) && info.dli_sname) {
131
            symbol = info.dli_sname;
132
        }
133
134
        fprintf(stderr, "%d: %p %s\n", idx, addr, symbol);
135
    }
136
}
137
#elif defined(__linux__) && defined(__GLIBC__)
138
#include <execinfo.h>
139
0
static void ggml_print_backtrace_symbols(void) {
140
0
    void * trace[100];
141
0
    int nptrs = backtrace(trace, sizeof(trace)/sizeof(trace[0]));
142
0
    backtrace_symbols_fd(trace, nptrs, STDERR_FILENO);
143
0
}
144
#elif defined(__APPLE__)
145
#include <execinfo.h>
146
static void ggml_print_backtrace_symbols(void) {
147
    void * trace[100];
148
    int nptrs = backtrace(trace, sizeof(trace)/sizeof(trace[0]));
149
    backtrace_symbols_fd(trace, nptrs, STDERR_FILENO);
150
}
151
#else
152
static void ggml_print_backtrace_symbols(void) {
153
    // platform not supported
154
}
155
#endif
156
157
0
void ggml_print_backtrace(void) {
158
0
    const char * GGML_NO_BACKTRACE = getenv("GGML_NO_BACKTRACE");
159
0
    if (GGML_NO_BACKTRACE) {
160
0
        return;
161
0
    }
162
#if defined(__APPLE__)
163
    // On macOS, fork+debugger attachment is problematic due to:
164
    // 1. libdispatch "poisons" forked child processes
165
    // 2. lldb has issues attaching to parent from forked child
166
    // Use simple backtrace() instead to avoid Terminal.app crashes
167
    const char * GGML_BACKTRACE_LLDB = getenv("GGML_BACKTRACE_LLDB");
168
    if (!GGML_BACKTRACE_LLDB) {
169
        fprintf(stderr, "WARNING: Using native backtrace. Set GGML_BACKTRACE_LLDB for more info.\n");
170
        fprintf(stderr, "WARNING: GGML_BACKTRACE_LLDB may cause native MacOS Terminal.app to crash.\n");
171
        fprintf(stderr, "See: https://github.com/ggml-org/llama.cpp/pull/17869\n");
172
        ggml_print_backtrace_symbols();
173
        return;
174
    }
175
#endif
176
0
#if defined(__linux__)
177
0
    FILE * f = fopen("/proc/self/status", "r");
178
0
    size_t size = 0;
179
0
    char * line = NULL;
180
0
    ssize_t length = 0;
181
0
    while ((length = getline(&line, &size, f)) > 0) {
182
0
        if (!strncmp(line, "TracerPid:", sizeof("TracerPid:") - 1) &&
183
0
            (length != sizeof("TracerPid:\t0\n") - 1 || line[length - 2] != '0')) {
184
            // Already being debugged, and the breakpoint is the later abort()
185
0
            free(line);
186
0
            fclose(f);
187
0
            return;
188
0
        }
189
0
    }
190
0
    free(line);
191
0
    fclose(f);
192
0
    int lock[2] = { -1, -1 };
193
0
    (void) !pipe(lock); // Don't start gdb until after PR_SET_PTRACER
194
0
#endif
195
0
    const int parent_pid = getpid();
196
0
    const int child_pid = fork();
197
0
    if (child_pid < 0) { // error
198
0
#if defined(__linux__)
199
0
        close(lock[1]);
200
0
        close(lock[0]);
201
0
#endif
202
0
        return;
203
0
    } else if (child_pid == 0) { // child
204
0
        char attach[32];
205
0
        snprintf(attach, sizeof(attach), "attach %d", parent_pid);
206
0
#if defined(__linux__)
207
0
        close(lock[1]);
208
0
        (void) !read(lock[0], lock, 1);
209
0
        close(lock[0]);
210
0
#endif
211
        // try gdb
212
0
        execlp("gdb", "gdb", "--batch",
213
0
            "-ex", "set style enabled on",
214
0
            "-ex", attach,
215
0
            "-ex", "bt -frame-info source-and-location",
216
0
            "-ex", "detach",
217
0
            "-ex", "quit",
218
0
            (char *) NULL);
219
        // try lldb
220
0
        execlp("lldb", "lldb", "--batch",
221
0
            "-o", "bt",
222
0
            "-o", "quit",
223
0
            "-p", &attach[sizeof("attach ") - 1],
224
0
            (char *) NULL);
225
        // gdb failed, fallback to backtrace_symbols
226
0
        ggml_print_backtrace_symbols();
227
0
        _Exit(0);
228
0
    } else { // parent
229
0
#if defined(__linux__)
230
0
        prctl(PR_SET_PTRACER, child_pid);
231
0
        close(lock[1]);
232
0
        close(lock[0]);
233
0
#endif
234
0
        waitpid(child_pid, NULL, 0);
235
0
    }
236
0
}
237
#else
238
void ggml_print_backtrace(void) {
239
    // platform not supported
240
}
241
#endif
242
243
static ggml_abort_callback_t g_abort_callback = NULL;
244
245
// Set the abort callback (passing null will restore original abort functionality: printing a message to stdout)
246
0
GGML_API ggml_abort_callback_t ggml_set_abort_callback(ggml_abort_callback_t callback) {
247
0
    ggml_abort_callback_t ret_val = g_abort_callback;
248
0
    g_abort_callback = callback;
249
0
    return ret_val;
250
0
}
251
252
0
void ggml_abort(const char * file, int line, const char * fmt, ...) {
253
0
    fflush(stdout);
254
255
0
    char message[2048];
256
0
    int offset = snprintf(message, sizeof(message), "%s:%d: ", file, line);
257
258
0
    va_list args;
259
0
    va_start(args, fmt);
260
0
    vsnprintf(message + offset, sizeof(message) - offset, fmt, args);
261
0
    va_end(args);
262
263
0
    if (g_abort_callback) {
264
0
        g_abort_callback(message);
265
0
    } else {
266
        // default: print error and backtrace to stderr
267
0
        fprintf(stderr, "%s\n", message);
268
        
269
0
    }
270
271
0
    abort();
272
0
}
273
274
// ggml_print_backtrace is registered with std::set_terminate by ggml.cpp
275
276
//
277
// logging
278
//
279
280
struct ggml_logger_state {
281
    ggml_log_callback log_callback;
282
    void * log_callback_user_data;
283
};
284
static struct ggml_logger_state g_logger_state = {ggml_log_callback_default, NULL};
285
286
0
static void ggml_log_internal_v(enum ggml_log_level level, const char * format, va_list args) {
287
0
    if (format == NULL) {
288
0
        return;
289
0
    }
290
0
    va_list args_copy;
291
0
    va_copy(args_copy, args);
292
0
    char buffer[128];
293
0
    int len = vsnprintf(buffer, 128, format, args);
294
0
    if (len < 128) {
295
0
        g_logger_state.log_callback(level, buffer, g_logger_state.log_callback_user_data);
296
0
    } else {
297
0
        char * buffer2 = (char *) calloc(len + 1, sizeof(char));
298
0
        vsnprintf(buffer2, len + 1, format, args_copy);
299
0
        buffer2[len] = 0;
300
0
        g_logger_state.log_callback(level, buffer2, g_logger_state.log_callback_user_data);
301
0
        free(buffer2);
302
0
    }
303
0
    va_end(args_copy);
304
0
}
305
306
0
void ggml_log_internal(enum ggml_log_level level, const char * format, ...) {
307
0
    va_list args;
308
0
    va_start(args, format);
309
0
    ggml_log_internal_v(level, format, args);
310
0
    va_end(args);
311
0
}
312
313
0
void ggml_log_callback_default(enum ggml_log_level level, const char * text, void * user_data) {
314
0
    (void) level;
315
0
    (void) user_data;
316
0
    fputs(text, stderr);
317
0
    fflush(stderr);
318
0
}
319
320
//
321
// end of logging block
322
//
323
324
#ifdef GGML_USE_ACCELERATE
325
// uncomment to use vDSP for soft max computation
326
// note: not sure if it is actually faster
327
//#define GGML_SOFT_MAX_ACCELERATE
328
#endif
329
330
331
0
void * ggml_aligned_malloc(size_t size) {
332
#if defined(__s390x__)
333
    const int alignment = 256;
334
#else
335
0
    const int alignment = 64;
336
0
#endif
337
338
#if defined(_MSC_VER) || defined(__MINGW32__)
339
    return _aligned_malloc(size, alignment);
340
#else
341
0
    if (size == 0) {
342
0
        GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_aligned_malloc!\n");
343
0
        return NULL;
344
0
    }
345
0
    void * aligned_memory = NULL;
346
  #ifdef GGML_USE_CPU_HBM
347
    int result = hbw_posix_memalign(&aligned_memory, alignment, size);
348
  #elif TARGET_OS_OSX
349
    GGML_UNUSED(alignment);
350
    kern_return_t alloc_status = vm_allocate((vm_map_t) mach_task_self(), (vm_address_t *) &aligned_memory, size, VM_FLAGS_ANYWHERE);
351
    int result = EFAULT;
352
    switch (alloc_status) {
353
        case KERN_SUCCESS:
354
            result = 0;
355
            break;
356
        case KERN_INVALID_ADDRESS:
357
            result = EINVAL;
358
            break;
359
        case KERN_NO_SPACE:
360
            result = ENOMEM;
361
            break;
362
        default:
363
            result = EFAULT;
364
            break;
365
    }
366
  #else
367
0
    int result = posix_memalign(&aligned_memory, alignment, size);
368
0
  #endif
369
0
    if (result != 0) {
370
        // Handle allocation failure
371
0
        const char *error_desc = "unknown allocation error";
372
0
        switch (result) {
373
0
            case EINVAL:
374
0
                error_desc = "invalid alignment value";
375
0
                break;
376
0
            case ENOMEM:
377
0
                error_desc = "insufficient memory";
378
0
                break;
379
0
        }
380
0
        GGML_LOG_ERROR("%s: %s (attempted to allocate %6.2f MB)\n", __func__, error_desc, size/(1024.0*1024.0));
381
0
        return NULL;
382
0
    }
383
0
    return aligned_memory;
384
0
#endif
385
0
}
386
387
0
void ggml_aligned_free(void * ptr, size_t size) {
388
0
    GGML_UNUSED(size);
389
#if defined(_MSC_VER) || defined(__MINGW32__)
390
    _aligned_free(ptr);
391
#elif GGML_USE_CPU_HBM
392
    if (ptr != NULL) {
393
        hbw_free(ptr);
394
    }
395
#elif TARGET_OS_OSX
396
    if (ptr != NULL) {
397
        vm_deallocate((vm_map_t)mach_task_self(), (vm_address_t)ptr, size);
398
    }
399
#else
400
0
    free(ptr);
401
0
#endif
402
0
}
403
404
405
0
inline static void * ggml_malloc(size_t size) {
406
0
    if (size == 0) {
407
0
        GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_malloc!\n");
408
0
        return NULL;
409
0
    }
410
0
    void * result = malloc(size);
411
0
    if (result == NULL) {
412
0
        GGML_LOG_ERROR("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
413
0
        GGML_ABORT("fatal error");
414
0
    }
415
0
    return result;
416
0
}
417
418
// calloc
419
0
inline static void * ggml_calloc(size_t num, size_t size) {
420
0
if ((num * size) > 9000000) {GGML_ABORT("calloc err");}
421
422
0
    if (num == 0 || size == 0) {
423
0
        GGML_LOG_WARN("Behavior may be unexpected when allocating 0 bytes for ggml_calloc!\n");
424
0
        return NULL;
425
0
    }
426
0
    void * result = calloc(num, size);
427
0
    if (result == NULL) {
428
0
        GGML_LOG_ERROR("%s: failed to allocate %6.2f MB\n", __func__, size/(1024.0*1024.0));
429
0
        GGML_ABORT("fatal error");
430
0
    }
431
0
    return result;
432
0
}
433
434
0
#define GGML_MALLOC(size)      ggml_malloc(size)
435
0
#define GGML_CALLOC(num, size) ggml_calloc(num, size)
436
437
0
#define GGML_FREE(ptr) free(ptr)
438
439
0
const char * ggml_status_to_string(enum ggml_status status) {
440
0
    switch (status) {
441
0
        case GGML_STATUS_ALLOC_FAILED: return "GGML status: error (failed to allocate memory)";
442
0
        case GGML_STATUS_FAILED:       return "GGML status: error (operation failed)";
443
0
        case GGML_STATUS_SUCCESS:      return "GGML status: success";
444
0
        case GGML_STATUS_ABORTED:      return "GGML status: warning (operation aborted)";
445
0
    }
446
447
0
    return "GGML status: unknown";
448
0
}
449
450
0
float ggml_fp16_to_fp32(ggml_fp16_t x) {
451
0
#define ggml_fp16_to_fp32 do_not_use__ggml_fp16_to_fp32__in_ggml
452
0
    return GGML_FP16_TO_FP32(x);
453
0
}
454
455
0
ggml_fp16_t ggml_fp32_to_fp16(float x) {
456
0
#define ggml_fp32_to_fp16 do_not_use__ggml_fp32_to_fp16__in_ggml
457
0
    return GGML_FP32_TO_FP16(x);
458
0
}
459
460
0
float ggml_bf16_to_fp32(ggml_bf16_t x) {
461
0
#define ggml_bf16_to_fp32 do_not_use__ggml_bf16_to_fp32__in_ggml
462
0
    return GGML_BF16_TO_FP32(x);  // it just left shifts
463
0
}
464
465
0
ggml_bf16_t ggml_fp32_to_bf16(float x) {
466
0
#define ggml_fp32_to_bf16 do_not_use__ggml_fp32_to_bf16__in_ggml
467
0
    return GGML_FP32_TO_BF16(x);
468
0
}
469
470
0
void ggml_fp16_to_fp32_row(const ggml_fp16_t * x, float * y, int64_t n) {
471
0
    for (int64_t i = 0; i < n; i++) {
472
0
        y[i] = GGML_FP16_TO_FP32(x[i]);
473
0
    }
474
0
}
475
476
0
void ggml_fp32_to_fp16_row(const float * x, ggml_fp16_t * y, int64_t n) {
477
0
    int i = 0;
478
0
    for (; i < n; ++i) {
479
0
        y[i] = GGML_FP32_TO_FP16(x[i]);
480
0
    }
481
0
}
482
483
0
void ggml_bf16_to_fp32_row(const ggml_bf16_t * x, float * y, int64_t n) {
484
0
    int i = 0;
485
0
    for (; i < n; ++i) {
486
0
        y[i] = GGML_BF16_TO_FP32(x[i]);
487
0
    }
488
0
}
489
490
0
void ggml_fp32_to_bf16_row_ref(const float * x, ggml_bf16_t * y, int64_t n) {
491
0
    for (int i = 0; i < n; i++) {
492
0
        y[i] = ggml_compute_fp32_to_bf16(x[i]);
493
0
    }
494
0
}
495
496
0
void ggml_fp32_to_bf16_row(const float * x, ggml_bf16_t * y, int64_t n) {
497
0
  int i = 0;
498
#if defined(__AVX512BF16__)
499
  // subnormals are flushed to zero on this platform
500
  for (; i + 32 <= n; i += 32) {
501
        _mm512_storeu_si512(
502
            (__m512i *)(y + i),
503
            m512i(_mm512_cvtne2ps_pbh(_mm512_loadu_ps(x + i + 16),
504
                                _mm512_loadu_ps(x + i))));
505
  }
506
#endif
507
0
    for (; i < n; i++) {
508
0
        y[i] = GGML_FP32_TO_BF16(x[i]);
509
0
    }
510
0
}
511
512
0
bool ggml_guid_matches(ggml_guid_t guid_a, ggml_guid_t guid_b) {
513
0
    return memcmp(guid_a, guid_b, sizeof(ggml_guid)) == 0;
514
0
}
515
516
0
const char * ggml_version(void) {
517
0
    return GGML_VERSION;
518
0
}
519
520
0
const char * ggml_commit(void) {
521
0
    return GGML_COMMIT;
522
0
}
523
524
//
525
// timing
526
//
527
528
#if defined(_MSC_VER) || defined(__MINGW32__)
529
static int64_t timer_freq, timer_start;
530
static BOOL CALLBACK ggml_time_init_once(PINIT_ONCE once, PVOID param, PVOID *ctx) {
531
    UNUSED(once);
532
    UNUSED(param);
533
    UNUSED(ctx);
534
535
    LARGE_INTEGER t;
536
    QueryPerformanceFrequency(&t);
537
    timer_freq = t.QuadPart;
538
539
    // The multiplication by 1000 or 1000000 below can cause an overflow if timer_freq
540
    // and the uptime is high enough.
541
    // We subtract the program start time to reduce the likelihood of that happening.
542
    QueryPerformanceCounter(&t);
543
    timer_start = t.QuadPart;
544
545
    return TRUE;
546
}
547
void ggml_time_init(void) {
548
    static INIT_ONCE once = INIT_ONCE_STATIC_INIT;
549
    InitOnceExecuteOnce(&once, ggml_time_init_once, NULL, NULL);
550
}
551
int64_t ggml_time_ms(void) {
552
    LARGE_INTEGER t;
553
    QueryPerformanceCounter(&t);
554
    return ((t.QuadPart-timer_start) * 1000) / timer_freq;
555
}
556
int64_t ggml_time_us(void) {
557
    LARGE_INTEGER t;
558
    QueryPerformanceCounter(&t);
559
    return ((t.QuadPart-timer_start) * 1000000) / timer_freq;
560
}
561
#else
562
0
void ggml_time_init(void) {}
563
0
int64_t ggml_time_ms(void) {
564
0
    struct timespec ts;
565
0
    clock_gettime(CLOCK_MONOTONIC, &ts);
566
0
    return (int64_t)ts.tv_sec*1000 + (int64_t)ts.tv_nsec/1000000;
567
0
}
568
569
0
int64_t ggml_time_us(void) {
570
0
    struct timespec ts;
571
0
    clock_gettime(CLOCK_MONOTONIC, &ts);
572
0
    return (int64_t)ts.tv_sec*1000000 + (int64_t)ts.tv_nsec/1000;
573
0
}
574
#endif
575
576
0
int64_t ggml_cycles(void) {
577
0
    return clock();
578
0
}
579
580
0
int64_t ggml_cycles_per_ms(void) {
581
0
    return CLOCKS_PER_SEC/1000;
582
0
}
583
584
//
585
// cross-platform UTF-8 file paths
586
//
587
588
#ifdef _WIN32
589
static wchar_t * ggml_mbstowcs(const char * mbs) {
590
    int wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, NULL, 0);
591
    if (!wlen) {
592
        errno = EINVAL;
593
        return NULL;
594
    }
595
596
    wchar_t * wbuf = GGML_MALLOC(wlen * sizeof(wchar_t));
597
    wlen = MultiByteToWideChar(CP_UTF8, 0, mbs, -1, wbuf, wlen);
598
    if (!wlen) {
599
        GGML_FREE(wbuf);
600
        errno = EINVAL;
601
        return NULL;
602
    }
603
604
    return wbuf;
605
}
606
#endif
607
608
0
FILE * ggml_fopen(const char * fname, const char * mode) {
609
#ifdef _WIN32
610
    FILE * file = NULL;
611
612
    // convert fname (UTF-8)
613
    wchar_t * wfname = ggml_mbstowcs(fname);
614
    if (wfname) {
615
        // convert mode (UTF-8)
616
        wchar_t * wmode = ggml_mbstowcs(mode);
617
        if (wmode) {
618
            // open file
619
            file = _wfopen(wfname, wmode);
620
            GGML_FREE(wmode);
621
        }
622
623
        GGML_FREE(wfname);
624
    }
625
626
    return file;
627
#else
628
0
    return fopen(fname, mode);
629
0
#endif
630
631
0
}
632
633
static const struct ggml_type_traits type_traits[GGML_TYPE_COUNT] = {
634
    [GGML_TYPE_I8] = {
635
        .type_name                = "i8",
636
        .blck_size                = 1,
637
        .type_size                = sizeof(int8_t),
638
        .is_quantized             = false,
639
    },
640
    [GGML_TYPE_I16] = {
641
        .type_name                = "i16",
642
        .blck_size                = 1,
643
        .type_size                = sizeof(int16_t),
644
        .is_quantized             = false,
645
    },
646
    [GGML_TYPE_I32] = {
647
        .type_name                = "i32",
648
        .blck_size                = 1,
649
        .type_size                = sizeof(int32_t),
650
        .is_quantized             = false,
651
    },
652
    [GGML_TYPE_I64] = {
653
        .type_name                = "i64",
654
        .blck_size                = 1,
655
        .type_size                = sizeof(int64_t),
656
        .is_quantized             = false,
657
    },
658
    [GGML_TYPE_F64] = {
659
        .type_name                = "f64",
660
        .blck_size                = 1,
661
        .type_size                = sizeof(double),
662
        .is_quantized             = false,
663
    },
664
    [GGML_TYPE_F32] = {
665
        .type_name                = "f32",
666
        .blck_size                = 1,
667
        .type_size                = sizeof(float),
668
        .is_quantized             = false,
669
    },
670
    [GGML_TYPE_F16] = {
671
        .type_name                = "f16",
672
        .blck_size                = 1,
673
        .type_size                = sizeof(ggml_fp16_t),
674
        .is_quantized             = false,
675
        .to_float                 = (ggml_to_float_t) ggml_fp16_to_fp32_row,
676
        .from_float_ref           = (ggml_from_float_t) ggml_fp32_to_fp16_row,
677
    },
678
    [GGML_TYPE_Q1_0] = {
679
        .type_name                = "q1_0",
680
        .blck_size                = QK1_0,
681
        .type_size                = sizeof(block_q1_0),
682
        .is_quantized             = true,
683
        .to_float                 = (ggml_to_float_t) dequantize_row_q1_0,
684
        .from_float_ref           = (ggml_from_float_t) quantize_row_q1_0_ref,
685
    },
686
    [GGML_TYPE_Q2_0] = {
687
        .type_name                = "q2_0",
688
        .blck_size                = QK2_0,
689
        .type_size                = sizeof(block_q2_0),
690
        .is_quantized             = true,
691
        .to_float                 = (ggml_to_float_t) dequantize_row_q2_0,
692
        .from_float_ref           = (ggml_from_float_t) quantize_row_q2_0_ref,
693
    },
694
    [GGML_TYPE_Q4_0] = {
695
        .type_name                = "q4_0",
696
        .blck_size                = QK4_0,
697
        .type_size                = sizeof(block_q4_0),
698
        .is_quantized             = true,
699
        .to_float                 = (ggml_to_float_t) dequantize_row_q4_0,
700
        .from_float_ref           = (ggml_from_float_t) quantize_row_q4_0_ref,
701
    },
702
    [GGML_TYPE_Q4_1] = {
703
        .type_name                = "q4_1",
704
        .blck_size                = QK4_1,
705
        .type_size                = sizeof(block_q4_1),
706
        .is_quantized             = true,
707
        .to_float                 = (ggml_to_float_t) dequantize_row_q4_1,
708
        .from_float_ref           = (ggml_from_float_t) quantize_row_q4_1_ref,
709
    },
710
    [4] = { // GGML_TYPE_Q4_2
711
        .type_name                = "DEPRECATED",
712
        .blck_size                = 0,
713
        .type_size                = 0,
714
        .is_quantized             = false,
715
    },
716
    [5] = { // GGML_TYPE_Q4_3
717
        .type_name                = "DEPRECATED",
718
        .blck_size                = 0,
719
        .type_size                = 0,
720
        .is_quantized             = false,
721
    },
722
    [GGML_TYPE_Q5_0] = {
723
        .type_name                = "q5_0",
724
        .blck_size                = QK5_0,
725
        .type_size                = sizeof(block_q5_0),
726
        .is_quantized             = true,
727
        .to_float                 = (ggml_to_float_t) dequantize_row_q5_0,
728
        .from_float_ref           = (ggml_from_float_t) quantize_row_q5_0_ref,
729
    },
730
    [GGML_TYPE_Q5_1] = {
731
        .type_name                = "q5_1",
732
        .blck_size                = QK5_1,
733
        .type_size                = sizeof(block_q5_1),
734
        .is_quantized             = true,
735
        .to_float                 = (ggml_to_float_t) dequantize_row_q5_1,
736
        .from_float_ref           = (ggml_from_float_t) quantize_row_q5_1_ref,
737
    },
738
    [GGML_TYPE_Q8_0] = {
739
        .type_name                = "q8_0",
740
        .blck_size                = QK8_0,
741
        .type_size                = sizeof(block_q8_0),
742
        .is_quantized             = true,
743
        .to_float                 = (ggml_to_float_t) dequantize_row_q8_0,
744
        .from_float_ref           = (ggml_from_float_t) quantize_row_q8_0_ref,
745
    },
746
    [GGML_TYPE_Q8_1] = {
747
        .type_name                = "q8_1",
748
        .blck_size                = QK8_1,
749
        .type_size                = sizeof(block_q8_1),
750
        .is_quantized             = true,
751
        .from_float_ref           = (ggml_from_float_t) quantize_row_q8_1_ref,
752
    },
753
    [GGML_TYPE_MXFP4] = {
754
        .type_name                = "mxfp4",
755
        .blck_size                = QK_MXFP4,
756
        .type_size                = sizeof(block_mxfp4),
757
        .is_quantized             = true,
758
        .to_float                 = (ggml_to_float_t) dequantize_row_mxfp4,
759
        .from_float_ref           = (ggml_from_float_t)quantize_row_mxfp4_ref,
760
    },
761
    [GGML_TYPE_NVFP4] = {
762
        .type_name                = "nvfp4",
763
        .blck_size                = QK_NVFP4,
764
        .type_size                = sizeof(block_nvfp4),
765
        .is_quantized             = true,
766
        .to_float                 = (ggml_to_float_t) dequantize_row_nvfp4,
767
        .from_float_ref           = (ggml_from_float_t)quantize_row_nvfp4_ref,
768
    },
769
    [GGML_TYPE_Q2_K] = {
770
        .type_name                = "q2_K",
771
        .blck_size                = QK_K,
772
        .type_size                = sizeof(block_q2_K),
773
        .is_quantized             = true,
774
        .to_float                 = (ggml_to_float_t) dequantize_row_q2_K,
775
        .from_float_ref           = (ggml_from_float_t) quantize_row_q2_K_ref,
776
    },
777
    [GGML_TYPE_Q3_K] = {
778
        .type_name                = "q3_K",
779
        .blck_size                = QK_K,
780
        .type_size                = sizeof(block_q3_K),
781
        .is_quantized             = true,
782
        .to_float                 = (ggml_to_float_t) dequantize_row_q3_K,
783
        .from_float_ref           = (ggml_from_float_t) quantize_row_q3_K_ref,
784
    },
785
    [GGML_TYPE_Q4_K] = {
786
        .type_name                = "q4_K",
787
        .blck_size                = QK_K,
788
        .type_size                = sizeof(block_q4_K),
789
        .is_quantized             = true,
790
        .to_float                 = (ggml_to_float_t) dequantize_row_q4_K,
791
        .from_float_ref           = (ggml_from_float_t) quantize_row_q4_K_ref,
792
    },
793
    [GGML_TYPE_Q5_K] = {
794
        .type_name                = "q5_K",
795
        .blck_size                = QK_K,
796
        .type_size                = sizeof(block_q5_K),
797
        .is_quantized             = true,
798
        .to_float                 = (ggml_to_float_t) dequantize_row_q5_K,
799
        .from_float_ref           = (ggml_from_float_t) quantize_row_q5_K_ref,
800
    },
801
    [GGML_TYPE_Q6_K] = {
802
        .type_name                = "q6_K",
803
        .blck_size                = QK_K,
804
        .type_size                = sizeof(block_q6_K),
805
        .is_quantized             = true,
806
        .to_float                 = (ggml_to_float_t) dequantize_row_q6_K,
807
        .from_float_ref           = (ggml_from_float_t) quantize_row_q6_K_ref,
808
    },
809
    [GGML_TYPE_IQ2_XXS] = {
810
        .type_name                = "iq2_xxs",
811
        .blck_size                = QK_K,
812
        .type_size                = sizeof(block_iq2_xxs),
813
        .is_quantized             = true,
814
        .to_float                 = (ggml_to_float_t) dequantize_row_iq2_xxs,
815
        .from_float_ref           = NULL,
816
    },
817
    [GGML_TYPE_IQ2_XS] = {
818
        .type_name                = "iq2_xs",
819
        .blck_size                = QK_K,
820
        .type_size                = sizeof(block_iq2_xs),
821
        .is_quantized             = true,
822
        .to_float                 = (ggml_to_float_t) dequantize_row_iq2_xs,
823
        .from_float_ref           = NULL,
824
    },
825
    [GGML_TYPE_IQ3_XXS] = {
826
        .type_name                = "iq3_xxs",
827
        .blck_size                = QK_K,
828
        .type_size                = sizeof(block_iq3_xxs),
829
        .is_quantized             = true,
830
        .to_float                 = (ggml_to_float_t) dequantize_row_iq3_xxs,
831
        .from_float_ref           = (ggml_from_float_t)quantize_row_iq3_xxs_ref,
832
    },
833
    [GGML_TYPE_IQ3_S] = {
834
        .type_name                = "iq3_s",
835
        .blck_size                = QK_K,
836
        .type_size                = sizeof(block_iq3_s),
837
        .is_quantized             = true,
838
        .to_float                 = (ggml_to_float_t) dequantize_row_iq3_s,
839
        .from_float_ref           = (ggml_from_float_t)quantize_row_iq3_s_ref,
840
    },
841
    [GGML_TYPE_IQ2_S] = {
842
        .type_name                = "iq2_s",
843
        .blck_size                = QK_K,
844
        .type_size                = sizeof(block_iq2_s),
845
        .is_quantized             = true,
846
        .to_float                 = (ggml_to_float_t) dequantize_row_iq2_s,
847
        .from_float_ref           = (ggml_from_float_t)quantize_row_iq2_s_ref,
848
    },
849
    [GGML_TYPE_IQ1_S] = {
850
        .type_name                = "iq1_s",
851
        .blck_size                = QK_K,
852
        .type_size                = sizeof(block_iq1_s),
853
        .is_quantized             = true,
854
        .to_float                 = (ggml_to_float_t) dequantize_row_iq1_s,
855
        .from_float_ref           = NULL,
856
    },
857
    [GGML_TYPE_IQ1_M] = {
858
        .type_name                = "iq1_m",
859
        .blck_size                = QK_K,
860
        .type_size                = sizeof(block_iq1_m),
861
        .is_quantized             = true,
862
        .to_float                 = (ggml_to_float_t) dequantize_row_iq1_m,
863
        .from_float_ref           = NULL,
864
    },
865
    [GGML_TYPE_IQ4_NL] = {
866
        .type_name                = "iq4_nl",
867
        .blck_size                = QK4_NL,
868
        .type_size                = sizeof(block_iq4_nl),
869
        .is_quantized             = true,
870
        .to_float                 = (ggml_to_float_t) dequantize_row_iq4_nl,
871
        .from_float_ref           = (ggml_from_float_t)quantize_row_iq4_nl_ref,
872
    },
873
    [GGML_TYPE_IQ4_XS] = {
874
        .type_name                = "iq4_xs",
875
        .blck_size                = QK_K,
876
        .type_size                = sizeof(block_iq4_xs),
877
        .is_quantized             = true,
878
        .to_float                 = (ggml_to_float_t) dequantize_row_iq4_xs,
879
        .from_float_ref           = (ggml_from_float_t)quantize_row_iq4_xs_ref,
880
    },
881
    [GGML_TYPE_Q8_K] = {
882
        .type_name                = "q8_K",
883
        .blck_size                = QK_K,
884
        .type_size                = sizeof(block_q8_K),
885
        .is_quantized             = true,
886
    },
887
    [GGML_TYPE_BF16] = {
888
        .type_name                = "bf16",
889
        .blck_size                = 1,
890
        .type_size                = sizeof(ggml_bf16_t),
891
        .is_quantized             = false,
892
        .to_float                 = (ggml_to_float_t) ggml_bf16_to_fp32_row,
893
        .from_float_ref           = (ggml_from_float_t) ggml_fp32_to_bf16_row_ref,
894
    },
895
    [31] = { // GGML_TYPE_Q4_0_4_4
896
        .type_name                = "TYPE_Q4_0_4_4 REMOVED, use Q4_0 with runtime repacking",
897
        .blck_size                = 0,
898
        .type_size                = 0,
899
        .is_quantized             = false,
900
    },
901
    [32] = { // GGML_TYPE_Q4_0_4_8
902
        .type_name                = "TYPE_Q4_0_4_8 REMOVED, use Q4_0 with runtime repacking",
903
        .blck_size                = 0,
904
        .type_size                = 0,
905
        .is_quantized             = false,
906
    },
907
    [33] = { // GGML_TYPE_Q4_0_8_8
908
        .type_name                = "TYPE_Q4_0_8_8 REMOVED, use Q4_0 with runtime repacking",
909
        .blck_size                = 0,
910
        .type_size                = 0,
911
        .is_quantized             = false,
912
    },
913
    [GGML_TYPE_TQ1_0] = {
914
        .type_name                = "tq1_0",
915
        .blck_size                = QK_K,
916
        .type_size                = sizeof(block_tq1_0),
917
        .is_quantized             = true,
918
        .to_float                 = (ggml_to_float_t) dequantize_row_tq1_0,
919
        .from_float_ref           = (ggml_from_float_t) quantize_row_tq1_0_ref,
920
    },
921
    [GGML_TYPE_TQ2_0] = {
922
        .type_name                = "tq2_0",
923
        .blck_size                = QK_K,
924
        .type_size                = sizeof(block_tq2_0),
925
        .is_quantized             = true,
926
        .to_float                 = (ggml_to_float_t) dequantize_row_tq2_0,
927
        .from_float_ref           = (ggml_from_float_t) quantize_row_tq2_0_ref,
928
    },
929
    [36] = { // GGML_TYPE_IQ4_NL_4_4
930
        .type_name                = "TYPE_IQ4_NL_4_4 REMOVED, use IQ4_NL with runtime repacking",
931
        .blck_size                = 0,
932
        .type_size                = 0,
933
        .is_quantized             = false,
934
    },
935
    [37] = { // GGML_TYPE_IQ4_NL_4_8
936
        .type_name                = "TYPE_IQ4_NL_4_8 REMOVED, use IQ4_NL with runtime repacking",
937
        .blck_size                = 0,
938
        .type_size                = 0,
939
        .is_quantized             = false,
940
    },
941
    [38] = { // GGML_TYPE_IQ4_NL_8_8
942
        .type_name                = "TYPE_IQ4_NL_8_8 REMOVED, use IQ4_NL with runtime repacking",
943
        .blck_size                = 0,
944
        .type_size                = 0,
945
        .is_quantized             = false,
946
    },
947
};
948
949
0
const struct ggml_type_traits * ggml_get_type_traits(enum ggml_type type) {
950
0
    assert(type >= 0);
951
0
    assert(type < GGML_TYPE_COUNT);
952
0
    return &type_traits[type];
953
0
}
954
955
//
956
// ggml object
957
//
958
959
struct ggml_object {
960
    size_t offs;
961
    size_t size;
962
963
    struct ggml_object * next;
964
965
    enum ggml_object_type type;
966
967
    char padding[4];
968
};
969
970
static const size_t GGML_OBJECT_SIZE = sizeof(struct ggml_object);
971
972
//
973
// ggml context
974
//
975
976
struct ggml_context {
977
    size_t mem_size;
978
    void * mem_buffer;
979
    bool   mem_buffer_owned;
980
    bool   no_alloc;
981
982
    int    n_objects;
983
984
    struct ggml_object * objects_begin;
985
    struct ggml_object * objects_end;
986
};
987
988
//
989
// data types
990
//
991
992
static const char * GGML_OP_NAME[GGML_OP_COUNT] = {
993
    "NONE",
994
995
    "DUP",
996
    "ADD",
997
    "ADD_ID",
998
    "ADD1",
999
    "ACC",
1000
    "SUB",
1001
    "MUL",
1002
    "DIV",
1003
    "SQR",
1004
    "SQRT",
1005
    "LOG",
1006
    "SIN",
1007
    "COS",
1008
    "SUM",
1009
    "SUM_ROWS",
1010
    "CUMSUM",
1011
    "MEAN",
1012
    "ARGMAX",
1013
    "COUNT_EQUAL",
1014
    "REPEAT",
1015
    "REPEAT_BACK",
1016
    "CONCAT",
1017
    "SILU_BACK",
1018
    "NORM",
1019
    "RMS_NORM",
1020
    "RMS_NORM_BACK",
1021
    "GROUP_NORM",
1022
    "L2_NORM",
1023
1024
    "MUL_MAT",
1025
    "MUL_MAT_ID",
1026
    "OUT_PROD",
1027
1028
    "SCALE",
1029
    "SET",
1030
    "CPY",
1031
    "CONT",
1032
    "RESHAPE",
1033
    "VIEW",
1034
    "PERMUTE",
1035
    "TRANSPOSE",
1036
    "GET_ROWS",
1037
    "GET_ROWS_BACK",
1038
    "SET_ROWS",
1039
    "DIAG",
1040
    "DIAG_MASK_INF",
1041
    "DIAG_MASK_ZERO",
1042
    "SOFT_MAX",
1043
    "SOFT_MAX_BACK",
1044
    "ROPE",
1045
    "ROPE_BACK",
1046
    "CLAMP",
1047
    "CONV_TRANSPOSE_1D",
1048
    "IM2COL",
1049
    "IM2COL_BACK",
1050
    "IM2COL_3D",
1051
    "COL2IM_1D",
1052
    "CONV_2D",
1053
    "CONV_3D",
1054
    "CONV_2D_DW",
1055
    "CONV_TRANSPOSE_2D",
1056
    "POOL_1D",
1057
    "POOL_2D",
1058
    "POOL_2D_BACK",
1059
    "UPSCALE",
1060
    "PAD",
1061
    "PAD_REFLECT_1D",
1062
    "ROLL",
1063
    "ARANGE",
1064
    "TIMESTEP_EMBEDDING",
1065
    "ARGSORT",
1066
    "TOP_K",
1067
    "LEAKY_RELU",
1068
    "TRI",
1069
    "FILL",
1070
1071
    "FLASH_ATTN_EXT",
1072
    "FLASH_ATTN_BACK",
1073
    "SSM_CONV",
1074
    "SSM_SCAN",
1075
    "WIN_PART",
1076
    "WIN_UNPART",
1077
    "GET_REL_POS",
1078
    "ADD_REL_POS",
1079
    "RWKV_WKV6",
1080
    "GATED_LINEAR_ATTN",
1081
    "RWKV_WKV7",
1082
    "SOLVE_TRI",
1083
    "GATED_DELTA_NET",
1084
    "LIGHTNING_INDEXER",
1085
1086
    "UNARY",
1087
1088
    "MAP_CUSTOM1",
1089
    "MAP_CUSTOM2",
1090
    "MAP_CUSTOM3",
1091
1092
    "CUSTOM",
1093
1094
    "CROSS_ENTROPY_LOSS",
1095
    "CROSS_ENTROPY_LOSS_BACK",
1096
    "OPT_STEP_ADAMW",
1097
    "OPT_STEP_SGD",
1098
1099
    "GLU",
1100
};
1101
1102
static_assert(GGML_OP_COUNT == 98, "GGML_OP_COUNT != 98");
1103
1104
static const char * GGML_OP_SYMBOL[GGML_OP_COUNT] = {
1105
    "none",
1106
1107
    "x",
1108
    "x+y",
1109
    "x[i]+y",
1110
    "x+y",
1111
    "view(x,nb,offset)+=y->x",
1112
    "x-y",
1113
    "x*y",
1114
    "x/y",
1115
    "x^2",
1116
    "√x",
1117
    "log(x)",
1118
    "sin(x)",
1119
    "cos(x)",
1120
    "Σx",
1121
    "Σx_k",
1122
    "cumsum(x)",
1123
    "Σx/n",
1124
    "argmax(x)",
1125
    "count_equal(x)",
1126
    "repeat(x)",
1127
    "repeat_back(x)",
1128
    "concat(x, y)",
1129
    "silu_back(x)",
1130
    "norm(x)",
1131
    "rms_norm(x)",
1132
    "rms_norm_back(x)",
1133
    "group_norm(x)",
1134
    "l2_norm(x)",
1135
1136
    "X*Y",
1137
    "X[i]*Y",
1138
    "X*Y",
1139
1140
    "x*v",
1141
    "y-\\>view(x)",
1142
    "x-\\>y",
1143
    "cont(x)",
1144
    "reshape(x)",
1145
    "view(x)",
1146
    "permute(x)",
1147
    "transpose(x)",
1148
    "get_rows(x)",
1149
    "get_rows_back(x)",
1150
    "set_rows(x)",
1151
    "diag(x)",
1152
    "diag_mask_inf(x)",
1153
    "diag_mask_zero(x)",
1154
    "soft_max(x)",
1155
    "soft_max_back(x)",
1156
    "rope(x)",
1157
    "rope_back(x)",
1158
    "clamp(x)",
1159
    "conv_transpose_1d(x)",
1160
    "im2col(x)",
1161
    "im2col_back(x)",
1162
    "im2col_3d(x)",
1163
    "col2im_1d(x)",
1164
    "conv_2d(x)",
1165
    "conv_3d(x)",
1166
    "conv_2d_dw(x)",
1167
    "conv_transpose_2d(x)",
1168
    "pool_1d(x)",
1169
    "pool_2d(x)",
1170
    "pool_2d_back(x)",
1171
    "upscale(x)",
1172
    "pad(x)",
1173
    "pad_reflect_1d(x)",
1174
    "roll(x)",
1175
    "arange(start, stop, step)",
1176
    "timestep_embedding(timesteps, dim, max_period)",
1177
    "argsort(x)",
1178
    "top_k(x)",
1179
    "leaky_relu(x)",
1180
    "tri(x)",
1181
    "fill(x, c)",
1182
1183
    "flash_attn_ext(x)",
1184
    "flash_attn_back(x)",
1185
    "ssm_conv(x)",
1186
    "ssm_scan(x)",
1187
    "win_part(x)",
1188
    "win_unpart(x)",
1189
    "get_rel_pos(x)",
1190
    "add_rel_pos(x)",
1191
    "rwkv_wkv6(k, v, r, tf, td, s)",
1192
    "gated_linear_attn(k, v, q, gate, s)",
1193
    "rwkv_wkv7(r, w, k, v, a, b, s)",
1194
    "A X = B, A triangular, solve X",
1195
    "gated_delta_net(q, k, v, g, beta, s)",
1196
    "lightning_indexer(q, k, weights, mask)",
1197
1198
    "unary(x)",
1199
1200
    "map_custom(x)",
1201
    "map_custom(x,y)",
1202
    "map_custom(x,y,z)",
1203
1204
    "custom(x)",
1205
1206
    "cross_entropy_loss(x,y)",
1207
    "cross_entropy_loss_back(x,y)",
1208
    "adamw(x)",
1209
    "sgd(x)",
1210
1211
    "glu(x)",
1212
};
1213
1214
static_assert(GGML_OP_COUNT == 98, "GGML_OP_COUNT != 98");
1215
1216
static_assert(GGML_OP_POOL_COUNT == 2, "GGML_OP_POOL_COUNT != 2");
1217
1218
static const char * GGML_UNARY_OP_NAME[GGML_UNARY_OP_COUNT] = {
1219
    "ABS",
1220
    "SGN",
1221
    "NEG",
1222
    "STEP",
1223
    "TANH",
1224
    "ELU",
1225
    "RELU",
1226
    "SIGMOID",
1227
    "GELU",
1228
    "GELU_QUICK",
1229
    "SILU",
1230
    "HARDSWISH",
1231
    "HARDSIGMOID",
1232
    "EXP",
1233
    "EXPM1",
1234
    "SOFTPLUS",
1235
    "GELU_ERF",
1236
    "XIELU",
1237
    "FLOOR",
1238
    "CEIL",
1239
    "ROUND",
1240
    "TRUNC",
1241
};
1242
1243
static_assert(GGML_UNARY_OP_COUNT == 22, "GGML_UNARY_OP_COUNT != 22");
1244
1245
static const char * GGML_GLU_OP_NAME[GGML_GLU_OP_COUNT] = {
1246
    "REGLU",
1247
    "GEGLU",
1248
    "SWIGLU",
1249
    "SWIGLU_OAI",
1250
    "GEGLU_ERF",
1251
    "GEGLU_QUICK",
1252
};
1253
1254
static_assert(GGML_GLU_OP_COUNT == 6, "GGML_GLU_OP_COUNT != 6");
1255
1256
1257
static_assert(sizeof(struct ggml_object)%GGML_MEM_ALIGN == 0, "ggml_object size must be a multiple of GGML_MEM_ALIGN");
1258
static_assert(sizeof(struct ggml_tensor)%GGML_MEM_ALIGN == 0, "ggml_tensor size must be a multiple of GGML_MEM_ALIGN");
1259
1260
1261
////////////////////////////////////////////////////////////////////////////////
1262
1263
0
void ggml_print_object(const struct ggml_object * obj) {
1264
0
    GGML_LOG_INFO(" - ggml_object: type = %d, offset = %zu, size = %zu, next = %p\n",
1265
0
            obj->type, obj->offs, obj->size, (const void *) obj->next);
1266
0
}
1267
1268
0
void ggml_print_objects(const struct ggml_context * ctx) {
1269
0
    struct ggml_object * obj = ctx->objects_begin;
1270
1271
0
    GGML_LOG_INFO("%s: objects in context %p:\n", __func__, (const void *) ctx);
1272
1273
0
    while (obj != NULL) {
1274
0
        ggml_print_object(obj);
1275
0
        obj = obj->next;
1276
0
    }
1277
1278
0
    GGML_LOG_INFO("%s: --- end ---\n", __func__);
1279
0
}
1280
1281
0
int64_t ggml_nelements(const struct ggml_tensor * tensor) {
1282
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1283
1284
0
    return tensor->ne[0]*tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
1285
0
}
1286
1287
0
int64_t ggml_nrows(const struct ggml_tensor * tensor) {
1288
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1289
1290
0
    return tensor->ne[1]*tensor->ne[2]*tensor->ne[3];
1291
0
}
1292
1293
0
size_t ggml_nbytes(const struct ggml_tensor * tensor) {
1294
0
    for (int i = 0; i < GGML_MAX_DIMS; ++i) {
1295
0
        if (tensor->ne[i] <= 0) {
1296
0
            return 0;
1297
0
        }
1298
0
    }
1299
1300
0
    size_t nbytes;
1301
0
    const size_t blck_size = ggml_blck_size(tensor->type);
1302
0
    if (blck_size == 1) {
1303
0
        nbytes = ggml_type_size(tensor->type);
1304
0
        for (int i = 0; i < GGML_MAX_DIMS; ++i) {
1305
0
            nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
1306
0
        }
1307
0
    }
1308
0
    else {
1309
0
        nbytes = tensor->ne[0]*tensor->nb[0]/blck_size;
1310
0
        for (int i = 1; i < GGML_MAX_DIMS; ++i) {
1311
0
            nbytes += (tensor->ne[i] - 1)*tensor->nb[i];
1312
0
        }
1313
0
    }
1314
1315
0
    return nbytes;
1316
0
}
1317
1318
0
size_t ggml_nbytes_pad(const struct ggml_tensor * tensor) {
1319
0
    return GGML_PAD(ggml_nbytes(tensor), GGML_MEM_ALIGN);
1320
0
}
1321
1322
0
int64_t ggml_blck_size(enum ggml_type type) {
1323
0
    assert(type >= 0);
1324
0
    assert(type < GGML_TYPE_COUNT);
1325
0
    return type_traits[type].blck_size;
1326
0
}
1327
1328
0
size_t ggml_type_size(enum ggml_type type) {
1329
0
    assert(type >= 0);
1330
0
    assert(type < GGML_TYPE_COUNT);
1331
0
    return type_traits[type].type_size;
1332
0
}
1333
1334
0
size_t ggml_row_size(enum ggml_type type, int64_t ne) {
1335
0
    assert(type >= 0);
1336
0
    assert(type < GGML_TYPE_COUNT);
1337
0
    assert(ne % ggml_blck_size(type) == 0);
1338
0
    return ggml_type_size(type)*ne/ggml_blck_size(type);
1339
0
}
1340
1341
0
double ggml_type_sizef(enum ggml_type type) {
1342
0
    assert(type >= 0);
1343
0
    assert(type < GGML_TYPE_COUNT);
1344
0
    return ((double)(type_traits[type].type_size))/type_traits[type].blck_size;
1345
0
}
1346
1347
0
const char * ggml_type_name(enum ggml_type type) {
1348
0
    assert(type >= 0);
1349
0
    assert(type < GGML_TYPE_COUNT);
1350
0
    return type_traits[type].type_name;
1351
0
}
1352
1353
0
bool ggml_is_quantized(enum ggml_type type) {
1354
0
    assert(type >= 0);
1355
0
    assert(type < GGML_TYPE_COUNT);
1356
0
    return type_traits[type].is_quantized;
1357
0
}
1358
1359
0
const char * ggml_op_name(enum ggml_op op) {
1360
0
    return GGML_OP_NAME[op];
1361
0
}
1362
1363
0
const char * ggml_op_symbol(enum ggml_op op) {
1364
0
    return GGML_OP_SYMBOL[op];
1365
0
}
1366
1367
0
const char * ggml_unary_op_name(enum ggml_unary_op op) {
1368
0
    return GGML_UNARY_OP_NAME[op];
1369
0
}
1370
1371
0
const char * ggml_glu_op_name(enum ggml_glu_op op) {
1372
0
    return GGML_GLU_OP_NAME[op];
1373
0
}
1374
1375
0
const char * ggml_op_desc(const struct ggml_tensor * t) {
1376
0
    if (t->op == GGML_OP_UNARY) {
1377
0
        enum ggml_unary_op uop = ggml_get_unary_op(t);
1378
0
        return ggml_unary_op_name(uop);
1379
0
    }
1380
0
    if (t->op == GGML_OP_GLU) {
1381
0
        enum ggml_glu_op gop = ggml_get_glu_op(t);
1382
0
        return ggml_glu_op_name(gop);
1383
0
    }
1384
0
    return ggml_op_name(t->op);
1385
0
}
1386
1387
0
size_t ggml_element_size(const struct ggml_tensor * tensor) {
1388
0
    return ggml_type_size(tensor->type);
1389
0
}
1390
1391
0
bool ggml_is_scalar(const struct ggml_tensor * tensor) {
1392
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1393
1394
0
    return tensor->ne[0] == 1 && tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
1395
0
}
1396
1397
0
bool ggml_is_vector(const struct ggml_tensor * tensor) {
1398
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1399
1400
0
    return tensor->ne[1] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1;
1401
0
}
1402
1403
0
bool ggml_is_matrix(const struct ggml_tensor * tensor) {
1404
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1405
1406
0
    return tensor->ne[2] == 1 && tensor->ne[3] == 1;
1407
0
}
1408
1409
0
bool ggml_is_3d(const struct ggml_tensor * tensor) {
1410
0
    return tensor->ne[3] == 1;
1411
0
}
1412
1413
0
int ggml_n_dims(const struct ggml_tensor * tensor) {
1414
0
    for (int i = GGML_MAX_DIMS - 1; i >= 1; --i) {
1415
0
        if (tensor->ne[i] > 1) {
1416
0
            return i + 1;
1417
0
        }
1418
0
    }
1419
0
    return 1;
1420
0
}
1421
1422
0
enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype) {
1423
0
    enum ggml_type wtype = GGML_TYPE_COUNT;
1424
1425
0
    switch (ftype) {
1426
0
        case GGML_FTYPE_ALL_F32:              wtype = GGML_TYPE_F32;   break;
1427
0
        case GGML_FTYPE_MOSTLY_F16:           wtype = GGML_TYPE_F16;   break;
1428
0
        case GGML_FTYPE_MOSTLY_BF16:          wtype = GGML_TYPE_BF16;  break;
1429
0
        case GGML_FTYPE_MOSTLY_Q4_0:          wtype = GGML_TYPE_Q4_0;  break;
1430
0
        case GGML_FTYPE_MOSTLY_Q4_1:          wtype = GGML_TYPE_Q4_1;  break;
1431
0
        case GGML_FTYPE_MOSTLY_Q1_0:          wtype = GGML_TYPE_Q1_0;  break;
1432
0
        case GGML_FTYPE_MOSTLY_Q2_0:          wtype = GGML_TYPE_Q2_0;  break;
1433
0
        case GGML_FTYPE_MOSTLY_Q5_0:          wtype = GGML_TYPE_Q5_0;  break;
1434
0
        case GGML_FTYPE_MOSTLY_Q5_1:          wtype = GGML_TYPE_Q5_1;  break;
1435
0
        case GGML_FTYPE_MOSTLY_Q8_0:          wtype = GGML_TYPE_Q8_0;  break;
1436
0
        case GGML_FTYPE_MOSTLY_MXFP4:         wtype = GGML_TYPE_MXFP4; break;
1437
0
        case GGML_FTYPE_MOSTLY_NVFP4:         wtype = GGML_TYPE_NVFP4; break;
1438
0
        case GGML_FTYPE_MOSTLY_Q2_K:          wtype = GGML_TYPE_Q2_K;  break;
1439
0
        case GGML_FTYPE_MOSTLY_Q3_K:          wtype = GGML_TYPE_Q3_K;  break;
1440
0
        case GGML_FTYPE_MOSTLY_Q4_K:          wtype = GGML_TYPE_Q4_K;  break;
1441
0
        case GGML_FTYPE_MOSTLY_Q5_K:          wtype = GGML_TYPE_Q5_K;  break;
1442
0
        case GGML_FTYPE_MOSTLY_Q6_K:          wtype = GGML_TYPE_Q6_K;  break;
1443
0
        case GGML_FTYPE_MOSTLY_IQ2_XXS:       wtype = GGML_TYPE_IQ2_XXS;  break;
1444
0
        case GGML_FTYPE_MOSTLY_IQ2_XS:        wtype = GGML_TYPE_IQ2_XS;   break;
1445
0
        case GGML_FTYPE_MOSTLY_IQ3_XXS:       wtype = GGML_TYPE_IQ3_XXS;  break;
1446
0
        case GGML_FTYPE_MOSTLY_IQ1_S:         wtype = GGML_TYPE_IQ1_S;    break;
1447
0
        case GGML_FTYPE_MOSTLY_IQ1_M:         wtype = GGML_TYPE_IQ1_M;    break;
1448
0
        case GGML_FTYPE_MOSTLY_IQ4_NL:        wtype = GGML_TYPE_IQ4_NL;   break;
1449
0
        case GGML_FTYPE_MOSTLY_IQ4_XS:        wtype = GGML_TYPE_IQ4_XS;   break;
1450
0
        case GGML_FTYPE_MOSTLY_IQ3_S:         wtype = GGML_TYPE_IQ3_S;    break;
1451
0
        case GGML_FTYPE_MOSTLY_IQ2_S:         wtype = GGML_TYPE_IQ2_S;    break;
1452
0
        case GGML_FTYPE_UNKNOWN:              wtype = GGML_TYPE_COUNT; break;
1453
0
        case GGML_FTYPE_MOSTLY_Q4_1_SOME_F16: wtype = GGML_TYPE_COUNT; break;
1454
0
    }
1455
1456
0
    GGML_ASSERT(wtype != GGML_TYPE_COUNT);
1457
1458
0
    return wtype;
1459
0
}
1460
1461
0
size_t ggml_tensor_overhead(void) {
1462
0
    return GGML_OBJECT_SIZE + GGML_TENSOR_SIZE;
1463
0
}
1464
1465
0
bool ggml_is_transposed(const struct ggml_tensor * tensor) {
1466
0
    return tensor->nb[0] > tensor->nb[1];
1467
0
}
1468
1469
0
static bool ggml_is_contiguous_m_n(const struct ggml_tensor * tensor, int m, int n) {
1470
0
    size_t next_nb = ggml_type_size(tensor->type);
1471
0
    if (tensor->ne[0] != ggml_blck_size(tensor->type) && tensor->nb[0] != next_nb) {
1472
0
        return false;
1473
0
    }
1474
0
    next_nb *= tensor->ne[0]/ggml_blck_size(tensor->type);
1475
0
    for (int i = 1; i < n; i++) {
1476
0
        if (i > m) {
1477
0
            if (tensor->ne[i] != 1 && tensor->nb[i] != next_nb) {
1478
0
                return false;
1479
0
            }
1480
0
            next_nb *= tensor->ne[i];
1481
0
        } else {
1482
            // this dimension does not need to be contiguous
1483
0
            next_nb = tensor->ne[i]*tensor->nb[i];
1484
0
        }
1485
0
    }
1486
0
    return true;
1487
0
}
1488
1489
0
bool ggml_is_contiguous(const struct ggml_tensor * tensor) {
1490
0
    return ggml_is_contiguous_0(tensor);
1491
0
}
1492
1493
0
bool ggml_is_contiguous_0(const struct ggml_tensor * tensor) {
1494
0
    return ggml_is_contiguous_m_n(tensor, 0, GGML_MAX_DIMS);
1495
0
}
1496
1497
0
bool ggml_is_contiguous_1(const struct ggml_tensor * tensor) {
1498
0
    return ggml_is_contiguous_m_n(tensor, 1, GGML_MAX_DIMS);
1499
0
}
1500
1501
0
bool ggml_is_contiguous_2(const struct ggml_tensor * tensor) {
1502
0
    return ggml_is_contiguous_m_n(tensor, 2, GGML_MAX_DIMS);
1503
0
}
1504
1505
0
bool ggml_is_contiguous_to_1(const struct ggml_tensor * tensor) {
1506
0
    return ggml_is_contiguous_m_n(tensor, 0, 1);
1507
0
}
1508
1509
0
bool ggml_is_contiguous_to_2(const struct ggml_tensor * tensor) {
1510
0
    return ggml_is_contiguous_m_n(tensor, 0, 2);
1511
0
}
1512
1513
0
bool ggml_is_contiguous_to_3(const struct ggml_tensor * tensor) {
1514
0
    return ggml_is_contiguous_m_n(tensor, 0, 3);
1515
0
}
1516
1517
0
bool ggml_is_contiguously_allocated(const struct ggml_tensor * tensor) {
1518
0
    return ggml_nbytes(tensor) == ggml_nelements(tensor) * ggml_type_size(tensor->type)/ggml_blck_size(tensor->type);
1519
0
}
1520
1521
0
bool ggml_is_permuted(const struct ggml_tensor * tensor) {
1522
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1523
1524
0
    return tensor->nb[0] > tensor->nb[1] || tensor->nb[1] > tensor->nb[2] || tensor->nb[2] > tensor->nb[3];
1525
0
}
1526
1527
0
bool ggml_is_contiguous_channels(const struct ggml_tensor * tensor) {
1528
0
    return
1529
0
        tensor->nb[0] > tensor->nb[2] &&
1530
0
        tensor->nb[1] > tensor->nb[0] &&
1531
0
        tensor->nb[2] == ggml_type_size(tensor->type);
1532
0
}
1533
1534
0
bool ggml_is_contiguous_rows(const struct ggml_tensor * tensor) {
1535
0
    return
1536
0
        tensor->ne[0] == ggml_blck_size(tensor->type) ||
1537
0
        tensor->nb[0] == ggml_type_size(tensor->type);
1538
0
}
1539
1540
0
static inline bool ggml_is_padded_1d(const struct ggml_tensor * tensor) {
1541
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1542
1543
0
    return
1544
0
        tensor->nb[0] == ggml_type_size(tensor->type) &&
1545
0
        tensor->nb[2] == tensor->nb[1]*tensor->ne[1] &&
1546
0
        tensor->nb[3] == tensor->nb[2]*tensor->ne[2];
1547
0
}
1548
1549
0
bool ggml_is_empty(const struct ggml_tensor * tensor) {
1550
0
    for (int i = 0; i < GGML_MAX_DIMS; ++i) {
1551
0
        if (tensor->ne[i] == 0) {
1552
            // empty if any dimension has no elements
1553
0
            return true;
1554
0
        }
1555
0
    }
1556
0
    return false;
1557
0
}
1558
1559
0
bool ggml_are_same_shape(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
1560
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1561
1562
0
    return
1563
0
        (t0->ne[0] == t1->ne[0]) &&
1564
0
        (t0->ne[1] == t1->ne[1]) &&
1565
0
        (t0->ne[2] == t1->ne[2]) &&
1566
0
        (t0->ne[3] == t1->ne[3]);
1567
0
}
1568
1569
0
bool ggml_are_same_stride(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
1570
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1571
1572
0
    return
1573
0
        (t0->nb[0] == t1->nb[0]) &&
1574
0
        (t0->nb[1] == t1->nb[1]) &&
1575
0
        (t0->nb[2] == t1->nb[2]) &&
1576
0
        (t0->nb[3] == t1->nb[3]);
1577
0
}
1578
1579
0
bool ggml_is_view(const struct ggml_tensor * t) {
1580
0
    return ggml_impl_is_view(t);
1581
0
}
1582
1583
// check if t1 can be represented as a repetition of t0
1584
0
bool ggml_can_repeat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
1585
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1586
1587
0
    return ggml_is_empty(t0) ? ggml_is_empty(t1) :
1588
0
        (t1->ne[0]%t0->ne[0] == 0) &&
1589
0
        (t1->ne[1]%t0->ne[1] == 0) &&
1590
0
        (t1->ne[2]%t0->ne[2] == 0) &&
1591
0
        (t1->ne[3]%t0->ne[3] == 0);
1592
0
}
1593
1594
0
static inline bool ggml_can_repeat_rows(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
1595
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
1596
1597
0
    return (t0->ne[0] == t1->ne[0]) && ggml_can_repeat(t0, t1);
1598
0
}
1599
1600
// assert that pointer is aligned to GGML_MEM_ALIGN
1601
#define GGML_ASSERT_ALIGNED(ptr) \
1602
0
    GGML_ASSERT(((uintptr_t) (ptr))%GGML_MEM_ALIGN == 0)
1603
1604
////////////////////////////////////////////////////////////////////////////////
1605
1606
0
struct ggml_context * ggml_init(struct ggml_init_params params) {
1607
0
    bool is_first_call = true;
1608
1609
0
    ggml_critical_section_start();
1610
1611
0
    if (is_first_call) {
1612
        // initialize time system (required on Windows)
1613
0
        ggml_time_init();
1614
1615
0
        is_first_call = false;
1616
0
    }
1617
1618
0
    ggml_critical_section_end();
1619
1620
0
    struct ggml_context * ctx = GGML_MALLOC(sizeof(struct ggml_context));
1621
1622
    // allow to call ggml_init with 0 size
1623
0
    if (params.mem_size == 0) {
1624
0
        params.mem_size = GGML_MEM_ALIGN;
1625
0
    }
1626
1627
0
    const size_t mem_size = params.mem_buffer ? params.mem_size : GGML_PAD(params.mem_size, GGML_MEM_ALIGN);
1628
1629
0
    *ctx = (struct ggml_context) {
1630
0
        /*.mem_size           =*/ mem_size,
1631
0
        /*.mem_buffer         =*/ params.mem_buffer ? params.mem_buffer : ggml_aligned_malloc(mem_size),
1632
0
        /*.mem_buffer_owned   =*/ params.mem_buffer ? false : true,
1633
0
        /*.no_alloc           =*/ params.no_alloc,
1634
0
        /*.n_objects          =*/ 0,
1635
0
        /*.objects_begin      =*/ NULL,
1636
0
        /*.objects_end        =*/ NULL,
1637
0
    };
1638
1639
0
    GGML_ASSERT(ctx->mem_buffer != NULL);
1640
1641
0
    GGML_ASSERT_ALIGNED(ctx->mem_buffer);
1642
1643
0
    GGML_PRINT_DEBUG("%s: context initialized\n", __func__);
1644
1645
0
    return ctx;
1646
0
}
1647
1648
0
void ggml_reset(struct ggml_context * ctx) {
1649
0
    if (ctx == NULL) {
1650
0
        return;
1651
0
    }
1652
1653
0
    ctx->n_objects     = 0;
1654
0
    ctx->objects_begin = NULL;
1655
0
    ctx->objects_end   = NULL;
1656
0
}
1657
1658
0
void ggml_free(struct ggml_context * ctx) {
1659
0
    if (ctx == NULL) {
1660
0
        return;
1661
0
    }
1662
1663
0
    if (ctx->mem_buffer_owned) {
1664
0
        ggml_aligned_free(ctx->mem_buffer, ctx->mem_size);
1665
0
    }
1666
1667
0
    GGML_FREE(ctx);
1668
0
}
1669
1670
0
size_t ggml_used_mem(const struct ggml_context * ctx) {
1671
0
    return ctx->objects_end == NULL ? 0 : ctx->objects_end->offs + ctx->objects_end->size;
1672
0
}
1673
1674
0
bool ggml_get_no_alloc(struct ggml_context * ctx) {
1675
0
    return ctx->no_alloc;
1676
0
}
1677
1678
0
void ggml_set_no_alloc(struct ggml_context * ctx, bool no_alloc) {
1679
0
    ctx->no_alloc = no_alloc;
1680
0
}
1681
1682
0
void * ggml_get_mem_buffer(const struct ggml_context * ctx) {
1683
0
    return ctx->mem_buffer;
1684
0
}
1685
1686
0
size_t ggml_get_mem_size(const struct ggml_context * ctx) {
1687
0
    return ctx->mem_size;
1688
0
}
1689
1690
0
size_t ggml_get_max_tensor_size(const struct ggml_context * ctx) {
1691
0
    size_t max_size = 0;
1692
1693
0
    for (struct ggml_tensor * tensor = ggml_get_first_tensor(ctx); tensor != NULL; tensor = ggml_get_next_tensor(ctx, tensor)) {
1694
0
        size_t bytes = ggml_nbytes(tensor);
1695
0
        max_size = MAX(max_size, bytes);
1696
0
    }
1697
1698
0
    return max_size;
1699
0
}
1700
1701
////////////////////////////////////////////////////////////////////////////////
1702
1703
0
static struct ggml_object * ggml_new_object(struct ggml_context * ctx, enum ggml_object_type type, size_t size) {
1704
    // always insert objects at the end of the context's memory pool
1705
0
    struct ggml_object * obj_cur = ctx->objects_end;
1706
1707
0
    const size_t cur_offs = obj_cur == NULL ? 0 : obj_cur->offs;
1708
0
    const size_t cur_size = obj_cur == NULL ? 0 : obj_cur->size;
1709
0
    const size_t cur_end  = cur_offs + cur_size;
1710
1711
    // align to GGML_MEM_ALIGN
1712
0
    GGML_ASSERT(size <= SIZE_MAX - (GGML_MEM_ALIGN - 1));
1713
0
    size_t size_needed = GGML_PAD(size, GGML_MEM_ALIGN);
1714
1715
0
    char * const mem_buffer = ctx->mem_buffer;
1716
0
    struct ggml_object * const obj_new = (struct ggml_object *)(mem_buffer + cur_end);
1717
1718
    // integer overflow checks
1719
0
    if (cur_end > SIZE_MAX - size_needed) {
1720
0
        GGML_LOG_WARN("%s: overflow detected in cur_end (%zu) + size_needed (%zu)\n", __func__, cur_end, size_needed);
1721
0
        return NULL;
1722
0
    }
1723
0
    if (cur_end + size_needed > SIZE_MAX - GGML_OBJECT_SIZE) {
1724
0
        GGML_LOG_WARN("%s: overflow detected in cur_end (%zu) + size_needed (%zu) + GGML_OBJECT_SIZE (%zu)\n", __func__,
1725
0
                cur_end, size_needed, (size_t) GGML_OBJECT_SIZE);
1726
0
        return NULL;
1727
0
    }
1728
1729
0
    if (cur_end + size_needed + GGML_OBJECT_SIZE > ctx->mem_size) {
1730
0
        GGML_LOG_WARN("%s: not enough space in the context's memory pool (needed %zu, available %zu)\n",
1731
0
                __func__, cur_end + size_needed + GGML_OBJECT_SIZE, ctx->mem_size);
1732
#ifndef NDEBUG
1733
        GGML_ABORT("not enough space in the context's memory pool");
1734
#endif
1735
0
        return NULL;
1736
0
    }
1737
1738
0
    *obj_new = (struct ggml_object) {
1739
0
        .offs = cur_end + GGML_OBJECT_SIZE,
1740
0
        .size = size_needed,
1741
0
        .next = NULL,
1742
0
        .type = type,
1743
0
    };
1744
1745
0
    GGML_ASSERT_ALIGNED(mem_buffer + obj_new->offs);
1746
1747
0
    if (obj_cur != NULL) {
1748
0
        obj_cur->next = obj_new;
1749
0
    } else {
1750
        // this is the first object in this context
1751
0
        ctx->objects_begin = obj_new;
1752
0
    }
1753
1754
0
    ctx->objects_end = obj_new;
1755
1756
    //printf("%s: inserted new object at %zu, size = %zu\n", __func__, cur_end, obj_new->size);
1757
1758
0
    return obj_new;
1759
0
}
1760
1761
static struct ggml_tensor * ggml_new_tensor_impl(
1762
        struct ggml_context * ctx,
1763
        enum   ggml_type      type,
1764
        int                   n_dims,
1765
        const int64_t       * ne,
1766
        struct ggml_tensor  * view_src,
1767
0
        size_t                view_offs) {
1768
1769
0
    GGML_ASSERT(type >= 0 && type < GGML_TYPE_COUNT);
1770
0
    GGML_ASSERT(n_dims >= 1 && n_dims <= GGML_MAX_DIMS);
1771
1772
    // find the base tensor and absolute offset
1773
0
    if (view_src != NULL && view_src->view_src != NULL) {
1774
0
        view_offs += view_src->view_offs;
1775
0
        view_src   = view_src->view_src;
1776
0
    }
1777
1778
0
    size_t data_size = ggml_row_size(type, ne[0]);
1779
0
    for (int i = 1; i < n_dims; i++) {
1780
0
        data_size *= ne[i];
1781
0
    }
1782
1783
0
    GGML_ASSERT(view_src == NULL || data_size == 0 || data_size + view_offs <= ggml_nbytes(view_src));
1784
1785
0
    void * data = view_src != NULL ? view_src->data : NULL;
1786
0
    if (data != NULL) {
1787
0
        data = (char *) data + view_offs;
1788
0
    }
1789
1790
0
    size_t obj_alloc_size = 0;
1791
1792
0
    if (view_src == NULL && !ctx->no_alloc) {
1793
        // allocate tensor data in the context's memory pool
1794
0
        obj_alloc_size = data_size;
1795
0
    }
1796
1797
0
    GGML_ASSERT(GGML_TENSOR_SIZE <= SIZE_MAX - obj_alloc_size);
1798
1799
0
    struct ggml_object * const obj_new = ggml_new_object(ctx, GGML_OBJECT_TYPE_TENSOR, GGML_TENSOR_SIZE + obj_alloc_size);
1800
0
    GGML_ASSERT(obj_new);
1801
1802
0
    struct ggml_tensor * const result = (struct ggml_tensor *)((char *)ctx->mem_buffer + obj_new->offs);
1803
1804
0
    *result = (struct ggml_tensor) {
1805
0
        /*.type         =*/ type,
1806
0
        /*.buffer       =*/ NULL,
1807
0
        /*.ne           =*/ { 1, 1, 1, 1 },
1808
0
        /*.nb           =*/ { 0, 0, 0, 0 },
1809
0
        /*.op           =*/ GGML_OP_NONE,
1810
0
        /*.op_params    =*/ { 0 },
1811
0
        /*.flags        =*/ 0,
1812
0
        /*.src          =*/ { NULL },
1813
0
        /*.view_src     =*/ view_src,
1814
0
        /*.view_offs    =*/ view_offs,
1815
0
        /*.data         =*/ obj_alloc_size > 0 ? (void *)(result + 1) : data,
1816
0
        /*.name         =*/ { 0 },
1817
0
        /*.extra        =*/ NULL,
1818
0
        /*.padding      =*/ { 0 },
1819
0
    };
1820
1821
    // TODO: this should not be needed as long as we don't rely on aligned SIMD loads
1822
    //GGML_ASSERT_ALIGNED(result->data);
1823
1824
0
    for (int i = 0; i < n_dims; i++) {
1825
0
        result->ne[i] = ne[i];
1826
0
    }
1827
1828
0
    result->nb[0] = ggml_type_size(type);
1829
0
    result->nb[1] = result->nb[0]*(result->ne[0]/ggml_blck_size(type));
1830
0
    for (int i = 2; i < GGML_MAX_DIMS; i++) {
1831
0
        result->nb[i] = result->nb[i - 1]*result->ne[i - 1];
1832
0
    }
1833
1834
0
    ctx->n_objects++;
1835
1836
0
    return result;
1837
0
}
1838
1839
struct ggml_tensor * ggml_new_tensor(
1840
        struct ggml_context * ctx,
1841
        enum   ggml_type      type,
1842
        int                   n_dims,
1843
0
        const int64_t       * ne) {
1844
0
    return ggml_new_tensor_impl(ctx, type, n_dims, ne, NULL, 0);
1845
0
}
1846
1847
struct ggml_tensor * ggml_new_tensor_1d(
1848
        struct ggml_context * ctx,
1849
        enum   ggml_type      type,
1850
0
        int64_t ne0) {
1851
0
    return ggml_new_tensor(ctx, type, 1, &ne0);
1852
0
}
1853
1854
struct ggml_tensor * ggml_new_tensor_2d(
1855
        struct ggml_context * ctx,
1856
        enum   ggml_type      type,
1857
        int64_t ne0,
1858
0
        int64_t ne1) {
1859
0
    const int64_t ne[2] = { ne0, ne1 };
1860
0
    return ggml_new_tensor(ctx, type, 2, ne);
1861
0
}
1862
1863
struct ggml_tensor * ggml_new_tensor_3d(
1864
        struct ggml_context * ctx,
1865
        enum   ggml_type      type,
1866
        int64_t ne0,
1867
        int64_t ne1,
1868
0
        int64_t ne2) {
1869
0
    const int64_t ne[3] = { ne0, ne1, ne2 };
1870
0
    return ggml_new_tensor(ctx, type, 3, ne);
1871
0
}
1872
1873
struct ggml_tensor * ggml_new_tensor_4d(
1874
        struct ggml_context * ctx,
1875
        enum   ggml_type type,
1876
        int64_t ne0,
1877
        int64_t ne1,
1878
        int64_t ne2,
1879
0
        int64_t ne3) {
1880
0
    const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
1881
0
    return ggml_new_tensor(ctx, type, 4, ne);
1882
0
}
1883
1884
0
void * ggml_new_buffer(struct ggml_context * ctx, size_t nbytes) {
1885
0
    struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_WORK_BUFFER, nbytes);
1886
1887
0
    return (uint8_t *)ctx->mem_buffer + obj->offs;
1888
0
}
1889
1890
0
struct ggml_tensor * ggml_dup_tensor(struct ggml_context * ctx, const struct ggml_tensor * src) {
1891
0
    return ggml_new_tensor(ctx, src->type, GGML_MAX_DIMS, src->ne);
1892
0
}
1893
1894
0
void ggml_unravel_index(const struct ggml_tensor * tensor, int64_t i, int64_t * i0, int64_t * i1, int64_t * i2, int64_t * i3) {
1895
0
    const int64_t ne2 = tensor->ne[2];
1896
0
    const int64_t ne1 = tensor->ne[1];
1897
0
    const int64_t ne0 = tensor->ne[0];
1898
1899
0
    const int64_t i3_ = (i/(ne2*ne1*ne0));
1900
0
    const int64_t i2_ = (i - i3_*ne2*ne1*ne0)/(ne1*ne0);
1901
0
    const int64_t i1_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0)/ne0;
1902
0
    const int64_t i0_ = (i - i3_*ne2*ne1*ne0 - i2_*ne1*ne0 - i1_*ne0);
1903
1904
0
    if (i0) {
1905
0
        * i0 = i0_;
1906
0
    }
1907
0
    if (i1) {
1908
0
        * i1 = i1_;
1909
0
    }
1910
0
    if (i2) {
1911
0
        * i2 = i2_;
1912
0
    }
1913
0
    if (i3) {
1914
0
        * i3 = i3_;
1915
0
    }
1916
0
}
1917
1918
0
void * ggml_get_data(const struct ggml_tensor * tensor) {
1919
0
    return tensor->data;
1920
0
}
1921
1922
0
float * ggml_get_data_f32(const struct ggml_tensor * tensor) {
1923
0
    assert(tensor->type == GGML_TYPE_F32);
1924
0
    return (float *)(tensor->data);
1925
0
}
1926
1927
0
enum ggml_unary_op ggml_get_unary_op(const struct ggml_tensor * tensor) {
1928
0
    GGML_ASSERT(tensor->op == GGML_OP_UNARY);
1929
0
    return (enum ggml_unary_op) ggml_get_op_params_i32(tensor, 0);
1930
0
}
1931
1932
0
enum ggml_glu_op ggml_get_glu_op(const struct ggml_tensor * tensor) {
1933
0
    GGML_ASSERT(tensor->op == GGML_OP_GLU);
1934
0
    return (enum ggml_glu_op) ggml_get_op_params_i32(tensor, 0);
1935
0
}
1936
1937
0
const char * ggml_get_name(const struct ggml_tensor * tensor) {
1938
0
    return tensor->name;
1939
0
}
1940
1941
0
struct ggml_tensor * ggml_set_name(struct ggml_tensor * tensor, const char * name) {
1942
0
    size_t i;
1943
0
    for (i = 0; i < sizeof(tensor->name) - 1 && name[i] != '\0'; i++) {
1944
0
        tensor->name[i] = name[i];
1945
0
    }
1946
0
    tensor->name[i] = '\0';
1947
0
    return tensor;
1948
0
}
1949
1950
0
struct ggml_tensor * ggml_format_name(struct ggml_tensor * tensor, const char * fmt, ...) {
1951
0
    va_list args;
1952
0
    va_start(args, fmt);
1953
0
    vsnprintf(tensor->name, sizeof(tensor->name), fmt, args);
1954
0
    va_end(args);
1955
0
    return tensor;
1956
0
}
1957
1958
struct ggml_tensor * ggml_view_tensor(
1959
        struct ggml_context * ctx,
1960
0
        struct ggml_tensor  * src) {
1961
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, src->type, GGML_MAX_DIMS, src->ne, src, 0);
1962
0
    ggml_format_name(result, "%s (view)", src->name);
1963
1964
0
    for (int i = 0; i < GGML_MAX_DIMS; i++) {
1965
0
        result->nb[i] = src->nb[i];
1966
0
    }
1967
1968
0
    return result;
1969
0
}
1970
1971
0
struct ggml_tensor * ggml_get_first_tensor(const struct ggml_context * ctx) {
1972
0
    struct ggml_object * obj = ctx->objects_begin;
1973
1974
0
    char * const mem_buffer = ctx->mem_buffer;
1975
1976
0
    while (obj != NULL) {
1977
0
        if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
1978
0
            return (struct ggml_tensor *)(mem_buffer + obj->offs);
1979
0
        }
1980
1981
0
        obj = obj->next;
1982
0
    }
1983
1984
0
    return NULL;
1985
0
}
1986
1987
0
struct ggml_tensor * ggml_get_next_tensor(const struct ggml_context * ctx, struct ggml_tensor * tensor) {
1988
0
    struct ggml_object * obj = (struct ggml_object *) ((char *)tensor - GGML_OBJECT_SIZE);
1989
0
    obj = obj->next;
1990
1991
0
    char * const mem_buffer = ctx->mem_buffer;
1992
1993
0
    while (obj != NULL) {
1994
0
        if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
1995
0
            return (struct ggml_tensor *)(mem_buffer + obj->offs);
1996
0
        }
1997
1998
0
        obj = obj->next;
1999
0
    }
2000
2001
0
    return NULL;
2002
0
}
2003
2004
0
struct ggml_tensor * ggml_get_tensor(struct ggml_context * ctx, const char * name) {
2005
0
    struct ggml_object * obj = ctx->objects_begin;
2006
2007
0
    char * const mem_buffer = ctx->mem_buffer;
2008
2009
0
    while (obj != NULL) {
2010
0
        if (obj->type == GGML_OBJECT_TYPE_TENSOR) {
2011
0
            struct ggml_tensor * cur = (struct ggml_tensor *)(mem_buffer + obj->offs);
2012
0
            if (strcmp(cur->name, name) == 0) {
2013
0
                return cur;
2014
0
            }
2015
0
        }
2016
2017
0
        obj = obj->next;
2018
0
    }
2019
2020
0
    return NULL;
2021
0
}
2022
2023
////////////////////////////////////////////////////////////////////////////////
2024
2025
// ggml_dup
2026
2027
static struct ggml_tensor * ggml_dup_impl(
2028
        struct ggml_context * ctx,
2029
        struct ggml_tensor  * a,
2030
0
        bool                  inplace) {
2031
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2032
2033
0
    result->op     = GGML_OP_DUP;
2034
0
    result->src[0] = a;
2035
2036
0
    return result;
2037
0
}
2038
2039
struct ggml_tensor * ggml_dup(
2040
        struct ggml_context * ctx,
2041
0
        struct ggml_tensor  * a) {
2042
0
    return ggml_dup_impl(ctx, a, false);
2043
0
}
2044
2045
struct ggml_tensor * ggml_dup_inplace(
2046
        struct ggml_context * ctx,
2047
0
        struct ggml_tensor  * a) {
2048
0
    return ggml_dup_impl(ctx, a, true);
2049
0
}
2050
2051
// ggml_add
2052
2053
static struct ggml_tensor * ggml_add_impl(
2054
        struct ggml_context * ctx,
2055
        struct ggml_tensor  * a,
2056
        struct ggml_tensor  * b,
2057
0
        bool                  inplace) {
2058
0
    GGML_ASSERT(ggml_can_repeat(b, a));
2059
2060
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2061
2062
0
    result->op     = GGML_OP_ADD;
2063
0
    result->src[0] = a;
2064
0
    result->src[1] = b;
2065
2066
0
    return result;
2067
0
}
2068
2069
struct ggml_tensor * ggml_add(
2070
        struct ggml_context * ctx,
2071
        struct ggml_tensor  * a,
2072
0
        struct ggml_tensor  * b) {
2073
0
    return ggml_add_impl(ctx, a, b, false);
2074
0
}
2075
2076
struct ggml_tensor * ggml_add_inplace(
2077
        struct ggml_context * ctx,
2078
        struct ggml_tensor  * a,
2079
0
        struct ggml_tensor  * b) {
2080
0
    return ggml_add_impl(ctx, a, b, true);
2081
0
}
2082
2083
// ggml_add_cast
2084
2085
static struct ggml_tensor * ggml_add_cast_impl(
2086
        struct ggml_context * ctx,
2087
        struct ggml_tensor  * a,
2088
        struct ggml_tensor  * b,
2089
0
        enum   ggml_type      type) {
2090
    // TODO: support less-strict constraint
2091
    //       GGML_ASSERT(ggml_can_repeat(b, a));
2092
0
    GGML_ASSERT(ggml_can_repeat_rows(b, a));
2093
2094
    // currently only supported for quantized input and f16
2095
0
    GGML_ASSERT(ggml_is_quantized(a->type) ||
2096
0
                a->type == GGML_TYPE_F16 ||
2097
0
                a->type == GGML_TYPE_BF16);
2098
2099
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
2100
2101
0
    result->op     = GGML_OP_ADD;
2102
0
    result->src[0] = a;
2103
0
    result->src[1] = b;
2104
2105
0
    return result;
2106
0
}
2107
2108
struct ggml_tensor * ggml_add_cast(
2109
        struct ggml_context * ctx,
2110
        struct ggml_tensor  * a,
2111
        struct ggml_tensor  * b,
2112
0
        enum   ggml_type      type) {
2113
0
    return ggml_add_cast_impl(ctx, a, b, type);
2114
0
}
2115
2116
struct ggml_tensor * ggml_add_id(
2117
            struct ggml_context * ctx,
2118
            struct ggml_tensor  * a,
2119
            struct ggml_tensor  * b,
2120
0
            struct ggml_tensor  * ids) {
2121
2122
0
    GGML_ASSERT(a->ne[0] == b->ne[0]);
2123
0
    GGML_ASSERT(a->ne[1] == ids->ne[0]);
2124
0
    GGML_ASSERT(a->ne[2] == ids->ne[1]);
2125
0
    GGML_ASSERT(ids->type == GGML_TYPE_I32);
2126
2127
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
2128
2129
0
    result->op     = GGML_OP_ADD_ID;
2130
0
    result->src[0] = a;
2131
0
    result->src[1] = b;
2132
0
    result->src[2] = ids;
2133
2134
0
    return result;
2135
0
}
2136
2137
// ggml_add1
2138
2139
static struct ggml_tensor * ggml_add1_impl(
2140
        struct ggml_context * ctx,
2141
        struct ggml_tensor  * a,
2142
        struct ggml_tensor  * b,
2143
0
        bool                  inplace) {
2144
0
    GGML_ASSERT(ggml_is_scalar(b));
2145
0
    GGML_ASSERT(ggml_is_padded_1d(a));
2146
2147
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2148
2149
0
    result->op     = GGML_OP_ADD1;
2150
0
    result->src[0] = a;
2151
0
    result->src[1] = b;
2152
2153
0
    return result;
2154
0
}
2155
2156
struct ggml_tensor * ggml_add1(
2157
        struct ggml_context * ctx,
2158
        struct ggml_tensor  * a,
2159
0
        struct ggml_tensor  * b) {
2160
0
    return ggml_add1_impl(ctx, a, b, false);
2161
0
}
2162
2163
struct ggml_tensor * ggml_add1_inplace(
2164
        struct ggml_context * ctx,
2165
        struct ggml_tensor  * a,
2166
0
        struct ggml_tensor  * b) {
2167
0
    return ggml_add1_impl(ctx, a, b, true);
2168
0
}
2169
2170
// ggml_acc
2171
2172
static struct ggml_tensor * ggml_acc_impl(
2173
        struct ggml_context * ctx,
2174
        struct ggml_tensor  * a,
2175
        struct ggml_tensor  * b,
2176
        size_t                nb1,
2177
        size_t                nb2,
2178
        size_t                nb3,
2179
        size_t                offset,
2180
0
        bool                  inplace) {
2181
0
    GGML_ASSERT(ggml_nelements(b) <= ggml_nelements(a));
2182
0
    GGML_ASSERT(ggml_is_contiguous(a));
2183
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
2184
0
    GGML_ASSERT(b->type == GGML_TYPE_F32);
2185
2186
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2187
2188
0
    int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
2189
0
    ggml_set_op_params(result, params, sizeof(params));
2190
2191
0
    result->op     = GGML_OP_ACC;
2192
0
    result->src[0] = a;
2193
0
    result->src[1] = b;
2194
2195
0
    return result;
2196
0
}
2197
2198
struct ggml_tensor * ggml_acc(
2199
        struct ggml_context * ctx,
2200
        struct ggml_tensor  * a,
2201
        struct ggml_tensor  * b,
2202
        size_t                nb1,
2203
        size_t                nb2,
2204
        size_t                nb3,
2205
0
        size_t                offset) {
2206
0
    return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
2207
0
}
2208
2209
struct ggml_tensor * ggml_acc_inplace(
2210
        struct ggml_context * ctx,
2211
        struct ggml_tensor  * a,
2212
        struct ggml_tensor  * b,
2213
        size_t                nb1,
2214
        size_t                nb2,
2215
        size_t                nb3,
2216
0
        size_t                offset) {
2217
0
    return ggml_acc_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
2218
0
}
2219
2220
// ggml_sub
2221
2222
static struct ggml_tensor * ggml_sub_impl(
2223
        struct ggml_context * ctx,
2224
        struct ggml_tensor  * a,
2225
        struct ggml_tensor  * b,
2226
0
        bool                  inplace) {
2227
0
    GGML_ASSERT(ggml_can_repeat(b, a));
2228
2229
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2230
2231
0
    result->op     = GGML_OP_SUB;
2232
0
    result->src[0] = a;
2233
0
    result->src[1] = b;
2234
2235
0
    return result;
2236
0
}
2237
2238
struct ggml_tensor * ggml_sub(
2239
        struct ggml_context * ctx,
2240
        struct ggml_tensor  * a,
2241
0
        struct ggml_tensor  * b) {
2242
0
    return ggml_sub_impl(ctx, a, b, false);
2243
0
}
2244
2245
struct ggml_tensor * ggml_sub_inplace(
2246
        struct ggml_context * ctx,
2247
        struct ggml_tensor  * a,
2248
0
        struct ggml_tensor  * b) {
2249
0
    return ggml_sub_impl(ctx, a, b, true);
2250
0
}
2251
2252
// ggml_mul
2253
2254
static struct ggml_tensor * ggml_mul_impl(
2255
        struct ggml_context * ctx,
2256
        struct ggml_tensor  * a,
2257
        struct ggml_tensor  * b,
2258
0
        bool                  inplace) {
2259
0
    GGML_ASSERT(ggml_can_repeat(b, a));
2260
2261
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2262
2263
0
    result->op     = GGML_OP_MUL;
2264
0
    result->src[0] = a;
2265
0
    result->src[1] = b;
2266
2267
0
    return result;
2268
0
}
2269
2270
struct ggml_tensor * ggml_mul(
2271
        struct ggml_context * ctx,
2272
        struct ggml_tensor  * a,
2273
0
        struct ggml_tensor  * b) {
2274
0
    return ggml_mul_impl(ctx, a, b, false);
2275
0
}
2276
2277
struct ggml_tensor * ggml_mul_inplace(
2278
        struct ggml_context * ctx,
2279
        struct ggml_tensor  * a,
2280
0
        struct ggml_tensor  * b) {
2281
0
    return ggml_mul_impl(ctx, a, b, true);
2282
0
}
2283
2284
// ggml_div
2285
2286
static struct ggml_tensor * ggml_div_impl(
2287
        struct ggml_context * ctx,
2288
        struct ggml_tensor  * a,
2289
        struct ggml_tensor  * b,
2290
0
        bool                  inplace) {
2291
0
    GGML_ASSERT(ggml_can_repeat(b, a));
2292
2293
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2294
2295
0
    result->op     = GGML_OP_DIV;
2296
0
    result->src[0] = a;
2297
0
    result->src[1] = b;
2298
2299
0
    return result;
2300
0
}
2301
2302
struct ggml_tensor * ggml_div(
2303
        struct ggml_context * ctx,
2304
        struct ggml_tensor  * a,
2305
0
        struct ggml_tensor  * b) {
2306
0
    return ggml_div_impl(ctx, a, b, false);
2307
0
}
2308
2309
struct ggml_tensor * ggml_div_inplace(
2310
        struct ggml_context * ctx,
2311
        struct ggml_tensor  * a,
2312
0
        struct ggml_tensor  * b) {
2313
0
    return ggml_div_impl(ctx, a, b, true);
2314
0
}
2315
2316
// ggml_sqr
2317
2318
static struct ggml_tensor * ggml_sqr_impl(
2319
        struct ggml_context * ctx,
2320
        struct ggml_tensor  * a,
2321
0
        bool                  inplace) {
2322
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2323
2324
0
    result->op     = GGML_OP_SQR;
2325
0
    result->src[0] = a;
2326
2327
0
    return result;
2328
0
}
2329
2330
struct ggml_tensor * ggml_sqr(
2331
        struct ggml_context * ctx,
2332
0
        struct ggml_tensor  * a) {
2333
0
    return ggml_sqr_impl(ctx, a, false);
2334
0
}
2335
2336
struct ggml_tensor * ggml_sqr_inplace(
2337
        struct ggml_context * ctx,
2338
0
        struct ggml_tensor  * a) {
2339
0
    return ggml_sqr_impl(ctx, a, true);
2340
0
}
2341
2342
// ggml_sqrt
2343
2344
static struct ggml_tensor * ggml_sqrt_impl(
2345
        struct ggml_context * ctx,
2346
        struct ggml_tensor  * a,
2347
0
        bool                  inplace) {
2348
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2349
2350
0
    result->op     = GGML_OP_SQRT;
2351
0
    result->src[0] = a;
2352
2353
0
    return result;
2354
0
}
2355
2356
struct ggml_tensor * ggml_sqrt(
2357
        struct ggml_context * ctx,
2358
0
        struct ggml_tensor  * a) {
2359
0
    return ggml_sqrt_impl(ctx, a, false);
2360
0
}
2361
2362
struct ggml_tensor * ggml_sqrt_inplace(
2363
        struct ggml_context * ctx,
2364
0
        struct ggml_tensor  * a) {
2365
0
    return ggml_sqrt_impl(ctx, a, true);
2366
0
}
2367
2368
// ggml_log
2369
2370
static struct ggml_tensor * ggml_log_impl(
2371
        struct ggml_context * ctx,
2372
        struct ggml_tensor  * a,
2373
0
        bool                  inplace) {
2374
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2375
2376
0
    result->op     = GGML_OP_LOG;
2377
0
    result->src[0] = a;
2378
2379
0
    return result;
2380
0
}
2381
2382
struct ggml_tensor * ggml_log(
2383
        struct ggml_context * ctx,
2384
0
        struct ggml_tensor  * a) {
2385
0
    return ggml_log_impl(ctx, a, false);
2386
0
}
2387
2388
struct ggml_tensor * ggml_log_inplace(
2389
        struct ggml_context * ctx,
2390
0
        struct ggml_tensor  * a) {
2391
0
    return ggml_log_impl(ctx, a, true);
2392
0
}
2393
2394
struct ggml_tensor * ggml_expm1(
2395
        struct ggml_context * ctx,
2396
0
        struct ggml_tensor  * a) {
2397
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_EXPM1);
2398
0
}
2399
2400
struct ggml_tensor * ggml_expm1_inplace(
2401
        struct ggml_context * ctx,
2402
0
        struct ggml_tensor  * a) {
2403
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXPM1);
2404
0
}
2405
2406
struct ggml_tensor * ggml_softplus(
2407
        struct ggml_context * ctx,
2408
0
        struct ggml_tensor  * a) {
2409
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_SOFTPLUS);
2410
0
}
2411
2412
struct ggml_tensor * ggml_softplus_inplace(
2413
        struct ggml_context * ctx,
2414
0
        struct ggml_tensor  * a) {
2415
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SOFTPLUS);
2416
0
}
2417
2418
// ggml_sin
2419
2420
static struct ggml_tensor * ggml_sin_impl(
2421
        struct ggml_context * ctx,
2422
        struct ggml_tensor  * a,
2423
0
        bool                  inplace) {
2424
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2425
2426
0
    result->op     = GGML_OP_SIN;
2427
0
    result->src[0] = a;
2428
2429
0
    return result;
2430
0
}
2431
2432
struct ggml_tensor * ggml_sin(
2433
        struct ggml_context * ctx,
2434
0
        struct ggml_tensor  * a) {
2435
0
    return ggml_sin_impl(ctx, a, false);
2436
0
}
2437
2438
struct ggml_tensor * ggml_sin_inplace(
2439
        struct ggml_context * ctx,
2440
0
        struct ggml_tensor  * a) {
2441
0
    return ggml_sin_impl(ctx, a, true);
2442
0
}
2443
2444
// ggml_cos
2445
2446
static struct ggml_tensor * ggml_cos_impl(
2447
        struct ggml_context * ctx,
2448
        struct ggml_tensor  * a,
2449
0
        bool                  inplace) {
2450
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2451
2452
0
    result->op     = GGML_OP_COS;
2453
0
    result->src[0] = a;
2454
2455
0
    return result;
2456
0
}
2457
2458
struct ggml_tensor * ggml_cos(
2459
        struct ggml_context * ctx,
2460
0
        struct ggml_tensor  * a) {
2461
0
    return ggml_cos_impl(ctx, a, false);
2462
0
}
2463
2464
struct ggml_tensor * ggml_cos_inplace(
2465
        struct ggml_context * ctx,
2466
0
        struct ggml_tensor  * a) {
2467
0
    return ggml_cos_impl(ctx, a, true);
2468
0
}
2469
2470
// ggml_sum
2471
2472
struct ggml_tensor * ggml_sum(
2473
        struct ggml_context * ctx,
2474
0
        struct ggml_tensor  * a) {
2475
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
2476
2477
0
    result->op     = GGML_OP_SUM;
2478
0
    result->src[0] = a;
2479
2480
0
    return result;
2481
0
}
2482
2483
// ggml_sum_rows
2484
2485
struct ggml_tensor * ggml_sum_rows(
2486
        struct ggml_context * ctx,
2487
0
        struct ggml_tensor  * a) {
2488
0
    int64_t ne[GGML_MAX_DIMS] = { 1 };
2489
0
    for (int i = 1; i < GGML_MAX_DIMS; ++i) {
2490
0
        ne[i] = a->ne[i];
2491
0
    }
2492
2493
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
2494
2495
0
    result->op     = GGML_OP_SUM_ROWS;
2496
0
    result->src[0] = a;
2497
2498
0
    return result;
2499
0
}
2500
2501
// ggml_cumsum
2502
2503
struct ggml_tensor * ggml_cumsum(
2504
        struct ggml_context * ctx,
2505
0
        struct ggml_tensor  * a) {
2506
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
2507
2508
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
2509
2510
0
    result->op     = GGML_OP_CUMSUM;
2511
0
    result->src[0] = a;
2512
2513
0
    return result;
2514
0
}
2515
2516
// ggml_mean
2517
2518
struct ggml_tensor * ggml_mean(
2519
        struct ggml_context * ctx,
2520
0
        struct ggml_tensor  * a) {
2521
0
    int64_t ne[4] = { 1, a->ne[1], a->ne[2], a->ne[3] };
2522
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
2523
2524
0
    result->op     = GGML_OP_MEAN;
2525
0
    result->src[0] = a;
2526
2527
0
    return result;
2528
0
}
2529
2530
// ggml_argmax
2531
2532
struct ggml_tensor * ggml_argmax(
2533
        struct ggml_context * ctx,
2534
0
        struct ggml_tensor  * a) {
2535
0
    GGML_ASSERT(ggml_is_matrix(a));
2536
0
    GGML_ASSERT(a->ne[0] <= INT32_MAX);
2537
2538
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, a->ne[1]);
2539
2540
0
    result->op     = GGML_OP_ARGMAX;
2541
0
    result->src[0] = a;
2542
2543
0
    return result;
2544
0
}
2545
2546
// ggml_count_equal
2547
2548
struct ggml_tensor * ggml_count_equal(
2549
        struct ggml_context * ctx,
2550
        struct ggml_tensor  * a,
2551
0
        struct ggml_tensor  * b) {
2552
0
    GGML_ASSERT(ggml_are_same_shape(a, b));
2553
2554
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, 1);
2555
2556
0
    result->op     = GGML_OP_COUNT_EQUAL;
2557
0
    result->src[0] = a;
2558
0
    result->src[1] = b;
2559
2560
0
    return result;
2561
0
}
2562
2563
// ggml_repeat
2564
2565
struct ggml_tensor * ggml_repeat(
2566
        struct ggml_context * ctx,
2567
        struct ggml_tensor  * a,
2568
0
        struct ggml_tensor  * b) {
2569
0
    GGML_ASSERT(ggml_can_repeat(a, b));
2570
2571
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
2572
2573
0
    result->op     = GGML_OP_REPEAT;
2574
0
    result->src[0] = a;
2575
2576
0
    return result;
2577
0
}
2578
2579
struct ggml_tensor * ggml_repeat_4d(
2580
        struct ggml_context * ctx,
2581
        struct ggml_tensor * a,
2582
0
        int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3) {
2583
0
    const bool can_repeat = ggml_is_empty(a) || (
2584
0
        (ne0 % a->ne[0] == 0) &&
2585
0
        (ne1 % a->ne[1] == 0) &&
2586
0
        (ne2 % a->ne[2] == 0) &&
2587
0
        (ne3 % a->ne[3] == 0)
2588
0
    );
2589
0
    GGML_ASSERT(can_repeat);
2590
2591
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
2592
2593
0
    result->op     = GGML_OP_REPEAT;
2594
0
    result->src[0] = a;
2595
2596
0
    return result;
2597
0
}
2598
2599
// ggml_repeat_back
2600
2601
struct ggml_tensor * ggml_repeat_back(
2602
        struct ggml_context * ctx,
2603
        struct ggml_tensor  * a,
2604
0
        struct ggml_tensor  * b) {
2605
0
    GGML_ASSERT(ggml_can_repeat(b, a));
2606
2607
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, b->ne);
2608
2609
0
    result->op     = GGML_OP_REPEAT_BACK;
2610
0
    result->src[0] = a;
2611
2612
0
    return result;
2613
0
}
2614
2615
// ggml_concat
2616
2617
struct ggml_tensor * ggml_concat(
2618
    struct ggml_context * ctx,
2619
    struct ggml_tensor  * a,
2620
    struct ggml_tensor  * b,
2621
0
    int                   dim) {
2622
0
    GGML_ASSERT(dim >= 0 && dim < GGML_MAX_DIMS);
2623
0
    GGML_ASSERT(a->type == b->type);
2624
2625
0
    int64_t ne[GGML_MAX_DIMS];
2626
0
    for (int d = 0; d < GGML_MAX_DIMS; ++d) {
2627
0
        if (d == dim) {
2628
0
            ne[d] = a->ne[d] + b->ne[d];
2629
0
            continue;
2630
0
        }
2631
0
        GGML_ASSERT(a->ne[d] == b->ne[d]);
2632
0
        ne[d] = a->ne[d];
2633
0
    }
2634
2635
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, GGML_MAX_DIMS, ne);
2636
2637
0
    ggml_set_op_params_i32(result, 0, dim);
2638
2639
0
    result->op     = GGML_OP_CONCAT;
2640
0
    result->src[0] = a;
2641
0
    result->src[1] = b;
2642
2643
0
    return result;
2644
0
}
2645
2646
// ggml_abs
2647
2648
struct ggml_tensor * ggml_abs(
2649
        struct ggml_context * ctx,
2650
0
        struct ggml_tensor  * a) {
2651
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_ABS);
2652
0
}
2653
2654
struct ggml_tensor * ggml_abs_inplace(
2655
        struct ggml_context * ctx,
2656
0
        struct ggml_tensor  * a) {
2657
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ABS);
2658
0
}
2659
2660
// ggml_sgn
2661
2662
struct ggml_tensor * ggml_sgn(
2663
        struct ggml_context * ctx,
2664
0
        struct ggml_tensor  * a) {
2665
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_SGN);
2666
0
}
2667
2668
struct ggml_tensor * ggml_sgn_inplace(
2669
        struct ggml_context * ctx,
2670
0
        struct ggml_tensor  * a) {
2671
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SGN);
2672
0
}
2673
2674
// ggml_neg
2675
2676
struct ggml_tensor * ggml_neg(
2677
        struct ggml_context * ctx,
2678
0
        struct ggml_tensor  * a) {
2679
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_NEG);
2680
0
}
2681
2682
struct ggml_tensor * ggml_neg_inplace(
2683
        struct ggml_context * ctx,
2684
0
        struct ggml_tensor  * a) {
2685
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_NEG);
2686
0
}
2687
2688
// ggml_step
2689
2690
struct ggml_tensor * ggml_step(
2691
        struct ggml_context * ctx,
2692
0
        struct ggml_tensor  * a) {
2693
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_STEP);
2694
0
}
2695
2696
struct ggml_tensor * ggml_step_inplace(
2697
        struct ggml_context * ctx,
2698
0
        struct ggml_tensor  * a) {
2699
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_STEP);
2700
0
}
2701
2702
// ggml_tanh
2703
2704
struct ggml_tensor * ggml_tanh(
2705
        struct ggml_context * ctx,
2706
0
        struct ggml_tensor  * a) {
2707
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_TANH);
2708
0
}
2709
2710
struct ggml_tensor * ggml_tanh_inplace(
2711
        struct ggml_context * ctx,
2712
0
        struct ggml_tensor  * a) {
2713
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TANH);
2714
0
}
2715
2716
// ggml_elu
2717
2718
struct ggml_tensor * ggml_elu(
2719
    struct ggml_context * ctx,
2720
0
    struct ggml_tensor  * a) {
2721
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_ELU);
2722
0
}
2723
2724
struct ggml_tensor * ggml_elu_inplace(
2725
    struct ggml_context * ctx,
2726
0
    struct ggml_tensor  * a) {
2727
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ELU);
2728
0
}
2729
2730
// ggml_relu
2731
2732
struct ggml_tensor * ggml_relu(
2733
        struct ggml_context * ctx,
2734
0
        struct ggml_tensor  * a) {
2735
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_RELU);
2736
0
}
2737
2738
struct ggml_tensor * ggml_relu_inplace(
2739
        struct ggml_context * ctx,
2740
0
        struct ggml_tensor  * a) {
2741
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_RELU);
2742
0
}
2743
2744
// ggml_leaky_relu
2745
2746
struct ggml_tensor * ggml_leaky_relu(
2747
        struct ggml_context * ctx,
2748
        struct ggml_tensor  * a,
2749
        float                 negative_slope,
2750
0
        bool                  inplace) {
2751
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
2752
2753
0
    ggml_set_op_params(result, &negative_slope, sizeof(negative_slope));
2754
2755
0
    result->op     = GGML_OP_LEAKY_RELU;
2756
0
    result->src[0] = a;
2757
2758
0
    return result;
2759
0
}
2760
2761
// ggml_sigmoid
2762
2763
struct ggml_tensor * ggml_sigmoid(
2764
        struct ggml_context * ctx,
2765
0
        struct ggml_tensor  * a) {
2766
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_SIGMOID);
2767
0
}
2768
2769
struct ggml_tensor * ggml_sigmoid_inplace(
2770
        struct ggml_context * ctx,
2771
0
        struct ggml_tensor  * a) {
2772
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SIGMOID);
2773
0
}
2774
2775
// ggml_gelu
2776
2777
struct ggml_tensor * ggml_gelu(
2778
        struct ggml_context * ctx,
2779
0
        struct ggml_tensor  * a) {
2780
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_GELU);
2781
0
}
2782
2783
struct ggml_tensor * ggml_gelu_inplace(
2784
        struct ggml_context * ctx,
2785
0
        struct ggml_tensor  * a) {
2786
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU);
2787
0
}
2788
2789
// ggml_gelu_erf
2790
2791
struct ggml_tensor * ggml_gelu_erf(
2792
        struct ggml_context * ctx,
2793
0
        struct ggml_tensor  * a) {
2794
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_ERF);
2795
0
}
2796
2797
struct ggml_tensor * ggml_gelu_erf_inplace(
2798
        struct ggml_context * ctx,
2799
0
        struct ggml_tensor  * a) {
2800
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_ERF);
2801
0
}
2802
2803
// ggml_gelu_quick
2804
2805
struct ggml_tensor * ggml_gelu_quick(
2806
        struct ggml_context * ctx,
2807
0
        struct ggml_tensor  * a) {
2808
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_GELU_QUICK);
2809
0
}
2810
2811
struct ggml_tensor * ggml_gelu_quick_inplace(
2812
        struct ggml_context * ctx,
2813
0
        struct ggml_tensor  * a) {
2814
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_GELU_QUICK);
2815
0
}
2816
2817
// ggml_silu
2818
2819
struct ggml_tensor * ggml_silu(
2820
        struct ggml_context * ctx,
2821
0
        struct ggml_tensor  * a) {
2822
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_SILU);
2823
0
}
2824
2825
struct ggml_tensor * ggml_silu_inplace(
2826
        struct ggml_context * ctx,
2827
0
        struct ggml_tensor  * a) {
2828
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_SILU);
2829
0
}
2830
2831
// ggml_xielu
2832
2833
struct ggml_tensor * ggml_xielu(
2834
        struct ggml_context * ctx,
2835
        struct ggml_tensor  * a,
2836
        float alpha_n,
2837
        float alpha_p,
2838
        float beta,
2839
0
        float eps) {
2840
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
2841
2842
0
    ggml_set_op_params_i32(result, 0, (int32_t) GGML_UNARY_OP_XIELU);
2843
0
    ggml_set_op_params_f32(result, 1, beta + ggml_compute_softplus_f32(alpha_n));
2844
0
    ggml_set_op_params_f32(result, 2, ggml_compute_softplus_f32(alpha_p));
2845
0
    ggml_set_op_params_f32(result, 3, beta);
2846
0
    ggml_set_op_params_f32(result, 4, eps);
2847
2848
0
    result->op     = GGML_OP_UNARY;
2849
0
    result->src[0] = a;
2850
2851
0
    return result;
2852
0
}
2853
2854
// ggml_silu_back
2855
2856
struct ggml_tensor * ggml_silu_back(
2857
        struct ggml_context * ctx,
2858
        struct ggml_tensor  * a,
2859
0
        struct ggml_tensor  * b) {
2860
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
2861
2862
0
    result->op     = GGML_OP_SILU_BACK;
2863
0
    result->src[0] = a;
2864
0
    result->src[1] = b;
2865
2866
0
    return result;
2867
0
}
2868
2869
// ggml hardswish
2870
2871
struct ggml_tensor * ggml_hardswish(
2872
        struct ggml_context * ctx,
2873
0
        struct ggml_tensor  * a) {
2874
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSWISH);
2875
0
}
2876
2877
// ggml hardsigmoid
2878
2879
struct ggml_tensor * ggml_hardsigmoid(
2880
        struct ggml_context * ctx,
2881
0
        struct ggml_tensor  * a) {
2882
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_HARDSIGMOID);
2883
0
}
2884
2885
// ggml exp
2886
2887
struct ggml_tensor * ggml_exp(
2888
        struct ggml_context * ctx,
2889
0
        struct ggml_tensor  * a) {
2890
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_EXP);
2891
0
}
2892
2893
struct ggml_tensor * ggml_exp_inplace(
2894
        struct ggml_context * ctx,
2895
0
        struct ggml_tensor  * a) {
2896
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_EXP);
2897
0
}
2898
2899
// ggml_glu
2900
2901
static struct ggml_tensor * ggml_glu_impl(
2902
        struct ggml_context * ctx,
2903
        struct ggml_tensor  * a,
2904
        struct ggml_tensor  * b,
2905
        enum ggml_glu_op      op,
2906
0
        bool                  swapped) {
2907
0
    GGML_ASSERT(ggml_is_contiguous_1(a));
2908
2909
0
    if (b) {
2910
0
        GGML_ASSERT(ggml_is_contiguous_1(b));
2911
0
        GGML_ASSERT(ggml_are_same_shape(a, b));
2912
0
        GGML_ASSERT(a->type == b->type);
2913
0
    }
2914
2915
0
    int64_t ne[GGML_MAX_DIMS] = { a->ne[0] / 2 }; for (int i = 1; i < GGML_MAX_DIMS; i++) ne[i] = a->ne[i];
2916
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b ? a->ne : ne, NULL, 0);
2917
2918
0
    ggml_set_op_params_i32(result, 0, (int32_t) op);
2919
0
    ggml_set_op_params_i32(result, 1, (int32_t) swapped);
2920
2921
0
    result->op     = GGML_OP_GLU;
2922
0
    result->src[0] = a;
2923
0
    result->src[1] = b;
2924
2925
0
    return result;
2926
0
}
2927
2928
// ggml_floor
2929
2930
struct ggml_tensor * ggml_floor(
2931
        struct ggml_context * ctx,
2932
0
        struct ggml_tensor  * a) {
2933
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_FLOOR);
2934
0
}
2935
2936
struct ggml_tensor * ggml_floor_inplace(
2937
        struct ggml_context * ctx,
2938
0
        struct ggml_tensor  * a) {
2939
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_FLOOR);
2940
0
}
2941
2942
// ggml_ceil
2943
2944
struct ggml_tensor * ggml_ceil(
2945
        struct ggml_context * ctx,
2946
0
        struct ggml_tensor  * a) {
2947
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_CEIL);
2948
0
}
2949
2950
struct ggml_tensor * ggml_ceil_inplace(
2951
        struct ggml_context * ctx,
2952
0
        struct ggml_tensor  * a) {
2953
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_CEIL);
2954
0
}
2955
2956
//ggml_round
2957
2958
struct ggml_tensor * ggml_round(
2959
        struct ggml_context * ctx,
2960
0
        struct ggml_tensor  * a) {
2961
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_ROUND);
2962
0
}
2963
2964
struct ggml_tensor * ggml_round_inplace(
2965
        struct ggml_context * ctx,
2966
0
        struct ggml_tensor  * a) {
2967
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_ROUND);
2968
0
}
2969
2970
//ggml_trunc
2971
2972
struct ggml_tensor * ggml_trunc(
2973
        struct ggml_context * ctx,
2974
0
        struct ggml_tensor  * a) {
2975
0
    return ggml_unary(ctx, a, GGML_UNARY_OP_TRUNC);
2976
0
}
2977
2978
struct ggml_tensor * ggml_trunc_inplace(
2979
        struct ggml_context * ctx,
2980
0
        struct ggml_tensor  * a) {
2981
0
    return ggml_unary_inplace(ctx, a, GGML_UNARY_OP_TRUNC);
2982
0
}
2983
2984
struct ggml_tensor * ggml_glu(
2985
        struct ggml_context * ctx,
2986
        struct ggml_tensor  * a,
2987
        enum ggml_glu_op      op,
2988
0
        bool                  swapped) {
2989
0
    return ggml_glu_impl(ctx, a, NULL, op, swapped);
2990
0
}
2991
2992
struct ggml_tensor * ggml_glu_split(
2993
        struct ggml_context * ctx,
2994
        struct ggml_tensor  * a,
2995
        struct ggml_tensor  * b,
2996
0
        enum ggml_glu_op      op) {
2997
0
    return ggml_glu_impl(ctx, a, b, op, false);
2998
0
}
2999
3000
// ggml_reglu
3001
3002
struct ggml_tensor * ggml_reglu(
3003
        struct ggml_context * ctx,
3004
0
        struct ggml_tensor  * a) {
3005
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_REGLU, false);
3006
0
}
3007
3008
struct ggml_tensor * ggml_reglu_swapped(
3009
        struct ggml_context * ctx,
3010
0
        struct ggml_tensor  * a) {
3011
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_REGLU, true);
3012
0
}
3013
3014
struct ggml_tensor * ggml_reglu_split(
3015
        struct ggml_context * ctx,
3016
        struct ggml_tensor  * a,
3017
0
        struct ggml_tensor  * b) {
3018
0
    return ggml_glu_impl(ctx, a, b, GGML_GLU_OP_REGLU, false);
3019
0
}
3020
3021
// ggml_geglu
3022
3023
struct ggml_tensor * ggml_geglu(
3024
        struct ggml_context * ctx,
3025
0
        struct ggml_tensor  * a) {
3026
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU, false);
3027
0
}
3028
3029
struct ggml_tensor * ggml_geglu_swapped(
3030
        struct ggml_context * ctx,
3031
0
        struct ggml_tensor  * a) {
3032
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU, true);
3033
0
}
3034
3035
struct ggml_tensor * ggml_geglu_split(
3036
        struct ggml_context * ctx,
3037
        struct ggml_tensor  * a,
3038
0
        struct ggml_tensor  * b) {
3039
0
    return ggml_glu_impl(ctx, a, b, GGML_GLU_OP_GEGLU, false);
3040
0
}
3041
3042
// ggml_swiglu
3043
3044
struct ggml_tensor * ggml_swiglu(
3045
        struct ggml_context * ctx,
3046
0
        struct ggml_tensor  * a) {
3047
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_SWIGLU, false);
3048
0
}
3049
3050
struct ggml_tensor * ggml_swiglu_swapped(
3051
        struct ggml_context * ctx,
3052
0
        struct ggml_tensor  * a) {
3053
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_SWIGLU, true);
3054
0
}
3055
3056
struct ggml_tensor * ggml_swiglu_split(
3057
        struct ggml_context * ctx,
3058
        struct ggml_tensor  * a,
3059
0
        struct ggml_tensor  * b) {
3060
0
    return ggml_glu_impl(ctx, a, b, GGML_GLU_OP_SWIGLU, false);
3061
0
}
3062
3063
// ggml_geglu_erf
3064
3065
struct ggml_tensor * ggml_geglu_erf(
3066
        struct ggml_context * ctx,
3067
0
        struct ggml_tensor  * a) {
3068
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU_ERF, false);
3069
0
}
3070
3071
struct ggml_tensor * ggml_geglu_erf_swapped(
3072
        struct ggml_context * ctx,
3073
0
        struct ggml_tensor  * a) {
3074
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU_ERF, true);
3075
0
}
3076
3077
struct ggml_tensor * ggml_geglu_erf_split(
3078
        struct ggml_context * ctx,
3079
        struct ggml_tensor  * a,
3080
0
        struct ggml_tensor  * b) {
3081
0
    return ggml_glu_impl(ctx, a, b, GGML_GLU_OP_GEGLU_ERF, false);
3082
0
}
3083
3084
// ggml_geglu_quick
3085
3086
struct ggml_tensor * ggml_geglu_quick(
3087
        struct ggml_context * ctx,
3088
0
        struct ggml_tensor  * a) {
3089
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU_QUICK, false);
3090
0
}
3091
3092
struct ggml_tensor * ggml_geglu_quick_swapped(
3093
        struct ggml_context * ctx,
3094
0
        struct ggml_tensor  * a) {
3095
0
    return ggml_glu_impl(ctx, a, NULL, GGML_GLU_OP_GEGLU_QUICK, true);
3096
0
}
3097
3098
struct ggml_tensor * ggml_geglu_quick_split(
3099
        struct ggml_context * ctx,
3100
        struct ggml_tensor  * a,
3101
0
        struct ggml_tensor  * b) {
3102
0
    return ggml_glu_impl(ctx, a, b, GGML_GLU_OP_GEGLU_QUICK, false);
3103
0
}
3104
3105
struct ggml_tensor * ggml_swiglu_oai(
3106
        struct ggml_context * ctx,
3107
        struct ggml_tensor  * a,
3108
        struct ggml_tensor  * b,
3109
        float                 alpha,
3110
0
        float                 limit) {
3111
0
    struct ggml_tensor * result = ggml_glu_impl(ctx, a, b, GGML_GLU_OP_SWIGLU_OAI, false);
3112
0
    ggml_set_op_params_f32(result, 2, alpha);
3113
0
    ggml_set_op_params_f32(result, 3, limit);
3114
3115
0
    return result;
3116
0
}
3117
3118
// ggml_norm
3119
3120
static struct ggml_tensor * ggml_norm_impl(
3121
        struct ggml_context * ctx,
3122
        struct ggml_tensor  * a,
3123
        float                 eps,
3124
0
        bool                  inplace) {
3125
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3126
3127
0
    ggml_set_op_params(result, &eps, sizeof(eps));
3128
3129
0
    result->op     = GGML_OP_NORM;
3130
0
    result->src[0] = a;
3131
3132
0
    return result;
3133
0
}
3134
3135
struct ggml_tensor * ggml_norm(
3136
        struct ggml_context * ctx,
3137
        struct ggml_tensor  * a,
3138
0
        float                 eps) {
3139
0
    return ggml_norm_impl(ctx, a, eps, false);
3140
0
}
3141
3142
struct ggml_tensor * ggml_norm_inplace(
3143
        struct ggml_context * ctx,
3144
        struct ggml_tensor  * a,
3145
0
        float                 eps) {
3146
0
    return ggml_norm_impl(ctx, a, eps, true);
3147
0
}
3148
3149
// ggml_rms_norm
3150
3151
static struct ggml_tensor * ggml_rms_norm_impl(
3152
        struct ggml_context * ctx,
3153
        struct ggml_tensor  * a,
3154
        float                 eps,
3155
0
        bool                  inplace) {
3156
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3157
3158
0
    ggml_set_op_params(result, &eps, sizeof(eps));
3159
3160
0
    result->op     = GGML_OP_RMS_NORM;
3161
0
    result->src[0] = a;
3162
3163
0
    return result;
3164
0
}
3165
3166
struct ggml_tensor * ggml_rms_norm(
3167
        struct ggml_context * ctx,
3168
        struct ggml_tensor  * a,
3169
0
        float                 eps) {
3170
0
    return ggml_rms_norm_impl(ctx, a, eps, false);
3171
0
}
3172
3173
struct ggml_tensor * ggml_rms_norm_inplace(
3174
        struct ggml_context * ctx,
3175
        struct ggml_tensor  * a,
3176
0
        float                 eps) {
3177
0
    return ggml_rms_norm_impl(ctx, a, eps, true);
3178
0
}
3179
3180
// ggml_rms_norm_back
3181
3182
struct ggml_tensor * ggml_rms_norm_back(
3183
        struct ggml_context * ctx,
3184
        struct ggml_tensor  * a,
3185
        struct ggml_tensor  * b,
3186
0
        float                 eps) {
3187
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
3188
3189
0
    ggml_set_op_params(result, &eps, sizeof(eps));
3190
3191
0
    result->op     = GGML_OP_RMS_NORM_BACK;
3192
0
    result->src[0] = a;
3193
0
    result->src[1] = b;
3194
3195
0
    return result;
3196
0
}
3197
3198
// ggml_group_norm
3199
3200
static struct ggml_tensor * ggml_group_norm_impl(
3201
        struct ggml_context * ctx,
3202
        struct ggml_tensor  * a,
3203
        int                   n_groups,
3204
        float                 eps,
3205
0
        bool                  inplace) {
3206
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3207
3208
0
    ggml_set_op_params_i32(result, 0, n_groups);
3209
0
    ggml_set_op_params_f32(result, 1, eps);
3210
3211
0
    result->op     = GGML_OP_GROUP_NORM;
3212
0
    result->src[0] = a;
3213
3214
0
    return result;
3215
0
}
3216
3217
struct ggml_tensor * ggml_group_norm(
3218
        struct ggml_context * ctx,
3219
        struct ggml_tensor  * a,
3220
        int                   n_groups,
3221
0
        float                 eps) {
3222
0
    return ggml_group_norm_impl(ctx, a, n_groups, eps, false);
3223
0
}
3224
3225
struct ggml_tensor * ggml_group_norm_inplace(
3226
        struct ggml_context * ctx,
3227
        struct ggml_tensor  * a,
3228
        int                   n_groups,
3229
0
        float                 eps) {
3230
0
    return ggml_group_norm_impl(ctx, a, n_groups, eps, true);
3231
0
}
3232
3233
// ggml_l2_norm
3234
3235
static struct ggml_tensor * ggml_l2_norm_impl(
3236
        struct ggml_context * ctx,
3237
        struct ggml_tensor  * a,
3238
        float                 eps,
3239
0
        bool                  inplace) {
3240
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3241
3242
0
    ggml_set_op_params_f32(result, 0, eps);
3243
3244
0
    result->op     = GGML_OP_L2_NORM;
3245
0
    result->src[0] = a;
3246
3247
0
    return result;
3248
0
}
3249
3250
struct ggml_tensor * ggml_l2_norm(
3251
        struct ggml_context * ctx,
3252
        struct ggml_tensor  * a,
3253
0
        float                 eps) {
3254
0
    return ggml_l2_norm_impl(ctx, a, eps, false);
3255
0
}
3256
3257
struct ggml_tensor * ggml_l2_norm_inplace(
3258
        struct ggml_context * ctx,
3259
        struct ggml_tensor  * a,
3260
0
        float                 eps) {
3261
0
    return ggml_l2_norm_impl(ctx, a, eps, true);
3262
0
}
3263
3264
// ggml_mul_mat
3265
3266
0
static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
3267
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
3268
3269
0
    return (t0->ne[0]           == t1->ne[0])  &&
3270
0
           (t1->ne[2]%t0->ne[2] == 0)          && // verify t0 is broadcastable
3271
0
           (t1->ne[3]%t0->ne[3] == 0);
3272
0
}
3273
3274
struct ggml_tensor * ggml_mul_mat(
3275
        struct ggml_context * ctx,
3276
        struct ggml_tensor  * a,
3277
0
        struct ggml_tensor  * b) {
3278
0
    GGML_ASSERT(ggml_can_mul_mat(a, b));
3279
0
    GGML_ASSERT(!ggml_is_transposed(a));
3280
3281
0
    const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
3282
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
3283
3284
0
    result->op     = GGML_OP_MUL_MAT;
3285
0
    result->src[0] = a;
3286
0
    result->src[1] = b;
3287
3288
0
    return result;
3289
0
}
3290
3291
void ggml_mul_mat_set_prec(
3292
        struct ggml_tensor * a,
3293
0
        enum ggml_prec       prec) {
3294
0
    GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
3295
3296
0
    const int32_t prec_i32 = (int32_t) prec;
3297
3298
0
    ggml_set_op_params_i32(a, 0, prec_i32);
3299
0
}
3300
3301
void ggml_mul_mat_set_hint(
3302
        struct ggml_tensor * a,
3303
0
        enum ggml_op_hint    hint) {
3304
0
    GGML_ASSERT(a->op == GGML_OP_MUL_MAT);
3305
3306
0
    const int32_t hint_i32 = (int32_t) hint;
3307
3308
0
    ggml_set_op_params_i32(a, 1, hint_i32);
3309
0
}
3310
3311
// ggml_mul_mat_id
3312
3313
/*
3314
    c = ggml_mul_mat_id(ctx, as, b, ids);
3315
3316
    as  -> [cols, rows, n_expert]
3317
    b   -> [cols, n_expert_used, n_tokens]
3318
    ids -> [n_expert_used, n_tokens] (i32)
3319
    c   -> [rows, n_expert_used, n_tokens]
3320
3321
    in b, n_expert_used can be broadcasted to match the n_expert_used of ids
3322
3323
    c ~= as[:,:,i] @ b[:,i%r,t], i = ids[e,t] for all e,t in ids
3324
*/
3325
struct ggml_tensor * ggml_mul_mat_id(
3326
        struct ggml_context * ctx,
3327
        struct ggml_tensor  * as,
3328
        struct ggml_tensor  * b,
3329
0
        struct ggml_tensor  * ids) {
3330
0
    GGML_ASSERT(!ggml_is_transposed(as));
3331
0
    GGML_ASSERT(ids->type == GGML_TYPE_I32);
3332
3333
0
    GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
3334
0
    GGML_ASSERT(b->ne[3] == 1); // b is 3d
3335
0
    GGML_ASSERT(ids->ne[2] == 1 && ids->ne[3] == 1); // ids is 2d
3336
0
    GGML_ASSERT(ids->ne[1] == b->ne[2]); // must have an expert list per b row
3337
0
    GGML_ASSERT(as->ne[0] == b->ne[0]); // can_mul_mat
3338
0
    GGML_ASSERT(ids->ne[0] % b->ne[1] == 0); // can broadcast
3339
3340
0
    const int64_t ne[4] = { as->ne[1], ids->ne[0], b->ne[2], 1 };
3341
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
3342
3343
0
    result->op     = GGML_OP_MUL_MAT_ID;
3344
0
    result->src[0] = as;
3345
0
    result->src[1] = b;
3346
0
    result->src[2] = ids;
3347
3348
0
    return result;
3349
0
}
3350
3351
// ggml_out_prod
3352
3353
0
static inline bool ggml_can_out_prod(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
3354
0
    static_assert(GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function");
3355
3356
0
    return (t0->ne[1] == t1->ne[1])   &&
3357
0
           (t1->ne[2]%t0->ne[2] == 0) && // verify t0 is broadcastable
3358
0
           (t1->ne[3]%t0->ne[3] == 0);
3359
0
}
3360
3361
struct ggml_tensor * ggml_out_prod(
3362
        struct ggml_context * ctx,
3363
        struct ggml_tensor  * a,
3364
0
        struct ggml_tensor  * b) {
3365
0
    GGML_ASSERT(ggml_can_out_prod(a, b));
3366
0
    GGML_ASSERT(!ggml_is_transposed(a));
3367
3368
    // a is broadcastable to b for ne[2] and ne[3] -> use b->ne[2] and b->ne[3]
3369
0
    const int64_t ne[4] = { a->ne[0], b->ne[0], b->ne[2], b->ne[3] };
3370
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
3371
3372
0
    result->op     = GGML_OP_OUT_PROD;
3373
0
    result->src[0] = a;
3374
0
    result->src[1] = b;
3375
3376
0
    return result;
3377
0
}
3378
3379
// ggml_scale
3380
3381
static struct ggml_tensor * ggml_scale_impl(
3382
        struct ggml_context * ctx,
3383
        struct ggml_tensor  * a,
3384
        float                 s,
3385
        float                 b,
3386
0
        bool                  inplace) {
3387
0
    GGML_ASSERT(ggml_is_padded_1d(a));
3388
3389
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3390
3391
0
    float params[2] = { s, b };
3392
0
    ggml_set_op_params(result, &params, sizeof(params));
3393
3394
0
    result->op     = GGML_OP_SCALE;
3395
0
    result->src[0] = a;
3396
3397
0
    return result;
3398
0
}
3399
3400
struct ggml_tensor * ggml_scale(
3401
        struct ggml_context * ctx,
3402
        struct ggml_tensor  * a,
3403
0
        float                 s) {
3404
0
    return ggml_scale_impl(ctx, a, s, 0.0, false);
3405
0
}
3406
3407
struct ggml_tensor * ggml_scale_inplace(
3408
        struct ggml_context * ctx,
3409
        struct ggml_tensor  * a,
3410
0
        float                 s) {
3411
0
    return ggml_scale_impl(ctx, a, s, 0.0, true);
3412
0
}
3413
3414
struct ggml_tensor * ggml_scale_bias(
3415
        struct ggml_context * ctx,
3416
        struct ggml_tensor  * a,
3417
        float                 s,
3418
0
        float                 b) {
3419
0
    return ggml_scale_impl(ctx, a, s, b, false);
3420
0
}
3421
3422
struct ggml_tensor * ggml_scale_bias_inplace(
3423
        struct ggml_context * ctx,
3424
        struct ggml_tensor  * a,
3425
        float                 s,
3426
0
        float                 b) {
3427
0
    return ggml_scale_impl(ctx, a, s, b, true);
3428
0
}
3429
3430
// ggml_set
3431
3432
static struct ggml_tensor * ggml_set_impl(
3433
        struct ggml_context * ctx,
3434
        struct ggml_tensor  * a,
3435
        struct ggml_tensor  * b,
3436
        size_t                nb1,
3437
        size_t                nb2,
3438
        size_t                nb3,
3439
        size_t                offset,
3440
0
        bool                  inplace) {
3441
0
    GGML_ASSERT(ggml_nelements(a) >= ggml_nelements(b));
3442
3443
    // make a view of the destination
3444
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3445
3446
0
    GGML_ASSERT(offset < (size_t)(1 << 30));
3447
0
    int32_t params[] = { nb1, nb2, nb3, offset, inplace ? 1 : 0 };
3448
0
    ggml_set_op_params(result, params, sizeof(params));
3449
3450
0
    result->op     = GGML_OP_SET;
3451
0
    result->src[0] = a;
3452
0
    result->src[1] = b;
3453
3454
0
    return result;
3455
0
}
3456
3457
struct ggml_tensor * ggml_set(
3458
        struct ggml_context * ctx,
3459
        struct ggml_tensor  * a,
3460
        struct ggml_tensor  * b,
3461
        size_t                nb1,
3462
        size_t                nb2,
3463
        size_t                nb3,
3464
0
        size_t                offset) {
3465
0
    return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, false);
3466
0
}
3467
3468
struct ggml_tensor * ggml_set_inplace(
3469
        struct ggml_context * ctx,
3470
        struct ggml_tensor  * a,
3471
        struct ggml_tensor  * b,
3472
        size_t                nb1,
3473
        size_t                nb2,
3474
        size_t                nb3,
3475
0
        size_t                offset) {
3476
0
    return ggml_set_impl(ctx, a, b, nb1, nb2, nb3, offset, true);
3477
0
}
3478
3479
struct ggml_tensor * ggml_set_1d(
3480
        struct ggml_context * ctx,
3481
        struct ggml_tensor  * a,
3482
        struct ggml_tensor  * b,
3483
0
        size_t                offset) {
3484
0
    return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, false);
3485
0
}
3486
3487
struct ggml_tensor * ggml_set_1d_inplace(
3488
        struct ggml_context * ctx,
3489
        struct ggml_tensor  * a,
3490
        struct ggml_tensor  * b,
3491
0
        size_t                offset) {
3492
0
    return ggml_set_impl(ctx, a, b, a->nb[1], a->nb[2], a->nb[3], offset, true);
3493
0
}
3494
3495
struct ggml_tensor * ggml_set_2d(
3496
        struct ggml_context * ctx,
3497
        struct ggml_tensor  * a,
3498
        struct ggml_tensor  * b,
3499
        size_t                nb1,
3500
0
        size_t                offset) {
3501
0
    return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, false);
3502
0
}
3503
3504
struct ggml_tensor * ggml_set_2d_inplace(
3505
        struct ggml_context * ctx,
3506
        struct ggml_tensor  * a,
3507
        struct ggml_tensor  * b,
3508
        size_t                nb1,
3509
0
        size_t                offset) {
3510
0
    return ggml_set_impl(ctx, a, b, nb1, a->nb[2], a->nb[3], offset, true);
3511
0
}
3512
3513
// ggml_cpy
3514
3515
static struct ggml_tensor * ggml_cpy_impl(
3516
        struct ggml_context * ctx,
3517
        struct ggml_tensor  * a,
3518
0
        struct ggml_tensor  * b) {
3519
0
    GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
3520
3521
    // make a view of the destination
3522
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, b);
3523
0
    if (strlen(b->name) > 0) {
3524
0
        ggml_format_name(result, "%s (copy of %s)", b->name, a->name);
3525
0
    } else {
3526
0
        ggml_format_name(result, "%s (copy)", a->name);
3527
0
    }
3528
3529
0
    result->op     = GGML_OP_CPY;
3530
0
    result->src[0] = a;
3531
0
    result->src[1] = b;
3532
3533
0
    return result;
3534
0
}
3535
3536
struct ggml_tensor * ggml_cpy(
3537
        struct ggml_context * ctx,
3538
        struct ggml_tensor * a,
3539
0
        struct ggml_tensor * b) {
3540
0
    return ggml_cpy_impl(ctx, a, b);
3541
0
}
3542
3543
struct ggml_tensor * ggml_cast(
3544
        struct ggml_context * ctx,
3545
        struct ggml_tensor  * a,
3546
0
        enum   ggml_type      type) {
3547
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, type, GGML_MAX_DIMS, a->ne);
3548
0
    ggml_format_name(result, "%s (copy)", a->name);
3549
3550
0
    result->op     = GGML_OP_CPY;
3551
0
    result->src[0] = a;
3552
0
    result->src[1] = result; // note: this self-reference might seem redundant, but it's actually needed by some
3553
                             //       backends for consistency with ggml_cpy_impl() above
3554
3555
0
    return result;
3556
0
}
3557
3558
// ggml_cont
3559
3560
static struct ggml_tensor * ggml_cont_impl(
3561
        struct ggml_context * ctx,
3562
0
        struct ggml_tensor  * a) {
3563
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
3564
0
    ggml_format_name(result, "%s (cont)", a->name);
3565
3566
0
    result->op     = GGML_OP_CONT;
3567
0
    result->src[0] = a;
3568
3569
0
    return result;
3570
0
}
3571
3572
struct ggml_tensor * ggml_cont(
3573
        struct ggml_context * ctx,
3574
0
        struct ggml_tensor * a) {
3575
0
    return ggml_cont_impl(ctx, a);
3576
0
}
3577
3578
// make contiguous, with new shape
3579
GGML_API struct ggml_tensor * ggml_cont_1d(
3580
        struct ggml_context * ctx,
3581
        struct ggml_tensor  * a,
3582
0
        int64_t               ne0) {
3583
0
    return ggml_cont_4d(ctx, a, ne0, 1, 1, 1);
3584
0
}
3585
3586
GGML_API struct ggml_tensor * ggml_cont_2d(
3587
        struct ggml_context * ctx,
3588
        struct ggml_tensor  * a,
3589
        int64_t               ne0,
3590
0
        int64_t               ne1) {
3591
0
    return ggml_cont_4d(ctx, a, ne0, ne1, 1, 1);
3592
0
}
3593
3594
GGML_API struct ggml_tensor * ggml_cont_3d(
3595
        struct ggml_context * ctx,
3596
        struct ggml_tensor  * a,
3597
        int64_t               ne0,
3598
        int64_t               ne1,
3599
0
        int64_t               ne2) {
3600
0
    return ggml_cont_4d(ctx, a, ne0, ne1, ne2, 1);
3601
0
}
3602
3603
struct ggml_tensor * ggml_cont_4d(
3604
        struct ggml_context * ctx,
3605
        struct ggml_tensor  * a,
3606
        int64_t               ne0,
3607
        int64_t               ne1,
3608
        int64_t               ne2,
3609
0
        int64_t               ne3) {
3610
0
    GGML_ASSERT(ggml_nelements(a) == (ne0*ne1*ne2*ne3));
3611
3612
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
3613
0
    ggml_format_name(result, "%s (cont)", a->name);
3614
3615
0
    result->op     = GGML_OP_CONT;
3616
0
    result->src[0] = a;
3617
3618
0
    return result;
3619
0
}
3620
3621
// ggml_reshape
3622
3623
struct ggml_tensor * ggml_reshape(
3624
        struct ggml_context * ctx,
3625
        struct ggml_tensor * a,
3626
0
        struct ggml_tensor * b) {
3627
0
    GGML_ASSERT(ggml_is_contiguous(a));
3628
    // as only the shape of b is relevant, and not its memory layout, b is allowed to be non contiguous.
3629
0
    GGML_ASSERT(ggml_nelements(a) == ggml_nelements(b));
3630
3631
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, GGML_MAX_DIMS, b->ne, a, 0);
3632
0
    ggml_format_name(result, "%s (reshaped)", a->name);
3633
3634
0
    result->op     = GGML_OP_RESHAPE;
3635
0
    result->src[0] = a;
3636
3637
0
    return result;
3638
0
}
3639
3640
struct ggml_tensor * ggml_reshape_1d(
3641
        struct ggml_context * ctx,
3642
        struct ggml_tensor  * a,
3643
0
        int64_t               ne0) {
3644
0
    GGML_ASSERT(ggml_is_contiguous(a));
3645
0
    GGML_ASSERT(ggml_nelements(a) == ne0);
3646
3647
0
    const int64_t ne[1] = { ne0 };
3648
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 1, ne, a, 0);
3649
0
    ggml_format_name(result, "%s (reshaped)", a->name);
3650
3651
0
    result->op     = GGML_OP_RESHAPE;
3652
0
    result->src[0] = a;
3653
3654
0
    return result;
3655
0
}
3656
3657
struct ggml_tensor * ggml_reshape_2d(
3658
        struct ggml_context * ctx,
3659
        struct ggml_tensor  * a,
3660
        int64_t               ne0,
3661
0
        int64_t               ne1) {
3662
0
    GGML_ASSERT(ggml_is_contiguous(a));
3663
0
    GGML_ASSERT(ggml_nelements(a) == ne0*ne1);
3664
3665
0
    const int64_t ne[2] = { ne0, ne1 };
3666
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 2, ne, a, 0);
3667
0
    ggml_format_name(result, "%s (reshaped)", a->name);
3668
3669
0
    result->op     = GGML_OP_RESHAPE;
3670
0
    result->src[0] = a;
3671
3672
0
    return result;
3673
0
}
3674
3675
struct ggml_tensor * ggml_reshape_3d(
3676
        struct ggml_context * ctx,
3677
        struct ggml_tensor  * a,
3678
        int64_t               ne0,
3679
        int64_t               ne1,
3680
0
        int64_t               ne2) {
3681
0
    GGML_ASSERT(ggml_is_contiguous(a));
3682
0
    GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2);
3683
3684
0
    const int64_t ne[3] = { ne0, ne1, ne2 };
3685
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 3, ne, a, 0);
3686
0
    ggml_format_name(result, "%s (reshaped)", a->name);
3687
3688
0
    result->op     = GGML_OP_RESHAPE;
3689
0
    result->src[0] = a;
3690
3691
0
    return result;
3692
0
}
3693
3694
struct ggml_tensor * ggml_reshape_4d(
3695
        struct ggml_context * ctx,
3696
        struct ggml_tensor  * a,
3697
        int64_t               ne0,
3698
        int64_t               ne1,
3699
        int64_t               ne2,
3700
0
        int64_t               ne3) {
3701
0
    GGML_ASSERT(ggml_is_contiguous(a));
3702
0
    GGML_ASSERT(ggml_nelements(a) == ne0*ne1*ne2*ne3);
3703
3704
0
    const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
3705
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, 4, ne, a, 0);
3706
0
    ggml_format_name(result, "%s (reshaped)", a->name);
3707
3708
0
    result->op     = GGML_OP_RESHAPE;
3709
0
    result->src[0] = a;
3710
3711
0
    return result;
3712
0
}
3713
3714
static struct ggml_tensor * ggml_view_impl(
3715
        struct ggml_context * ctx,
3716
        struct ggml_tensor  * a,
3717
        int                   n_dims,
3718
        const int64_t       * ne,
3719
0
        size_t                offset) {
3720
0
    struct ggml_tensor * result = ggml_new_tensor_impl(ctx, a->type, n_dims, ne, a, offset);
3721
0
    ggml_format_name(result, "%s (view)", a->name);
3722
3723
0
    ggml_set_op_params(result, &offset, sizeof(offset));
3724
3725
0
    result->op     = GGML_OP_VIEW;
3726
0
    result->src[0] = a;
3727
3728
0
    return result;
3729
0
}
3730
3731
// ggml_view_1d
3732
3733
struct ggml_tensor * ggml_view_1d(
3734
        struct ggml_context * ctx,
3735
        struct ggml_tensor  * a,
3736
        int64_t               ne0,
3737
0
        size_t                offset) {
3738
0
    struct ggml_tensor * result = ggml_view_impl(ctx, a, 1, &ne0, offset);
3739
3740
0
    return result;
3741
0
}
3742
3743
// ggml_view_2d
3744
3745
struct ggml_tensor * ggml_view_2d(
3746
        struct ggml_context * ctx,
3747
        struct ggml_tensor  * a,
3748
        int64_t               ne0,
3749
        int64_t               ne1,
3750
        size_t                nb1,
3751
0
        size_t                offset) {
3752
0
    const int64_t ne[2] = { ne0, ne1 };
3753
3754
0
    struct ggml_tensor * result = ggml_view_impl(ctx, a, 2, ne, offset);
3755
3756
0
    result->nb[1] = nb1;
3757
0
    result->nb[2] = result->nb[1]*ne1;
3758
0
    result->nb[3] = result->nb[2];
3759
3760
0
    return result;
3761
0
}
3762
3763
// ggml_view_3d
3764
3765
struct ggml_tensor * ggml_view_3d(
3766
        struct ggml_context * ctx,
3767
        struct ggml_tensor  * a,
3768
        int64_t               ne0,
3769
        int64_t               ne1,
3770
        int64_t               ne2,
3771
        size_t                nb1,
3772
        size_t                nb2,
3773
0
        size_t                offset) {
3774
0
    const int64_t ne[3] = { ne0, ne1, ne2 };
3775
3776
0
    struct ggml_tensor * result = ggml_view_impl(ctx, a, 3, ne, offset);
3777
3778
0
    result->nb[1] = nb1;
3779
0
    result->nb[2] = nb2;
3780
0
    result->nb[3] = result->nb[2]*ne2;
3781
3782
0
    return result;
3783
0
}
3784
3785
// ggml_view_4d
3786
3787
struct ggml_tensor * ggml_view_4d(
3788
        struct ggml_context * ctx,
3789
        struct ggml_tensor  * a,
3790
        int64_t               ne0,
3791
        int64_t               ne1,
3792
        int64_t               ne2,
3793
        int64_t               ne3,
3794
        size_t                nb1,
3795
        size_t                nb2,
3796
        size_t                nb3,
3797
0
        size_t                offset) {
3798
0
    const int64_t ne[4] = { ne0, ne1, ne2, ne3 };
3799
3800
0
    struct ggml_tensor * result = ggml_view_impl(ctx, a, 4, ne, offset);
3801
3802
0
    result->nb[1] = nb1;
3803
0
    result->nb[2] = nb2;
3804
0
    result->nb[3] = nb3;
3805
3806
0
    return result;
3807
0
}
3808
3809
// ggml_permute
3810
3811
struct ggml_tensor * ggml_permute(
3812
        struct ggml_context * ctx,
3813
        struct ggml_tensor  * a,
3814
        int                   axis0,
3815
        int                   axis1,
3816
        int                   axis2,
3817
0
        int                   axis3) {
3818
0
    GGML_ASSERT(axis0 >= 0 && axis0 < GGML_MAX_DIMS);
3819
0
    GGML_ASSERT(axis1 >= 0 && axis1 < GGML_MAX_DIMS);
3820
0
    GGML_ASSERT(axis2 >= 0 && axis2 < GGML_MAX_DIMS);
3821
0
    GGML_ASSERT(axis3 >= 0 && axis3 < GGML_MAX_DIMS);
3822
3823
0
    GGML_ASSERT(axis0 != axis1);
3824
0
    GGML_ASSERT(axis0 != axis2);
3825
0
    GGML_ASSERT(axis0 != axis3);
3826
0
    GGML_ASSERT(axis1 != axis2);
3827
0
    GGML_ASSERT(axis1 != axis3);
3828
0
    GGML_ASSERT(axis2 != axis3);
3829
3830
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
3831
0
    ggml_format_name(result, "%s (permuted)", a->name);
3832
3833
0
    int ne[GGML_MAX_DIMS];
3834
0
    int nb[GGML_MAX_DIMS];
3835
3836
0
    ne[axis0] = a->ne[0];
3837
0
    ne[axis1] = a->ne[1];
3838
0
    ne[axis2] = a->ne[2];
3839
0
    ne[axis3] = a->ne[3];
3840
3841
0
    nb[axis0] = a->nb[0];
3842
0
    nb[axis1] = a->nb[1];
3843
0
    nb[axis2] = a->nb[2];
3844
0
    nb[axis3] = a->nb[3];
3845
3846
0
    result->ne[0] = ne[0];
3847
0
    result->ne[1] = ne[1];
3848
0
    result->ne[2] = ne[2];
3849
0
    result->ne[3] = ne[3];
3850
3851
0
    result->nb[0] = nb[0];
3852
0
    result->nb[1] = nb[1];
3853
0
    result->nb[2] = nb[2];
3854
0
    result->nb[3] = nb[3];
3855
3856
0
    result->op     = GGML_OP_PERMUTE;
3857
0
    result->src[0] = a;
3858
3859
0
    int32_t params[] = { axis0, axis1, axis2, axis3 };
3860
0
    ggml_set_op_params(result, params, sizeof(params));
3861
3862
0
    return result;
3863
0
}
3864
3865
// ggml_transpose
3866
3867
struct ggml_tensor * ggml_transpose(
3868
        struct ggml_context * ctx,
3869
0
        struct ggml_tensor  * a) {
3870
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
3871
0
    ggml_format_name(result, "%s (transposed)", a->name);
3872
3873
0
    result->ne[0] = a->ne[1];
3874
0
    result->ne[1] = a->ne[0];
3875
3876
0
    result->nb[0] = a->nb[1];
3877
0
    result->nb[1] = a->nb[0];
3878
3879
0
    result->op     = GGML_OP_TRANSPOSE;
3880
0
    result->src[0] = a;
3881
3882
0
    return result;
3883
0
}
3884
3885
// ggml_get_rows
3886
3887
struct ggml_tensor * ggml_get_rows(
3888
        struct ggml_context * ctx,
3889
        struct ggml_tensor  * a,
3890
0
        struct ggml_tensor  * b) {
3891
0
    GGML_ASSERT(a->ne[2] == b->ne[1]);
3892
0
    GGML_ASSERT(a->ne[3] == b->ne[2]);
3893
0
    GGML_ASSERT(b->ne[3] == 1);
3894
0
    GGML_ASSERT(b->type == GGML_TYPE_I32);
3895
3896
    // TODO: implement non F32 return
3897
0
    enum ggml_type type = GGML_TYPE_F32;
3898
0
    if (a->type == GGML_TYPE_I32) {
3899
0
        type = a->type;
3900
0
    }
3901
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, a->ne[0], b->ne[0], b->ne[1], b->ne[2]);
3902
3903
0
    result->op     = GGML_OP_GET_ROWS;
3904
0
    result->src[0] = a;
3905
0
    result->src[1] = b;
3906
3907
0
    return result;
3908
0
}
3909
3910
// ggml_get_rows_back
3911
3912
struct ggml_tensor * ggml_get_rows_back(
3913
        struct ggml_context * ctx,
3914
        struct ggml_tensor  * a,
3915
        struct ggml_tensor  * b,
3916
0
        struct ggml_tensor  * c) {
3917
0
    GGML_ASSERT(ggml_is_matrix(a) && ggml_is_vector(b) && b->type == GGML_TYPE_I32);
3918
0
    GGML_ASSERT(ggml_is_matrix(c) && (a->ne[0] == c->ne[0]));
3919
3920
    // TODO: implement non F32 return
3921
    //struct ggml_tensor * result = ggml_new_tensor_2d(ctx, a->type, a->ne[0], b->ne[0]);
3922
0
    struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, c->ne[0], c->ne[1]);
3923
3924
0
    result->op     = GGML_OP_GET_ROWS_BACK;
3925
0
    result->src[0] = a;
3926
0
    result->src[1] = b;
3927
3928
0
    return result;
3929
0
}
3930
3931
// ggml_set_rows
3932
3933
struct ggml_tensor * ggml_set_rows(
3934
        struct ggml_context * ctx,
3935
        struct ggml_tensor  * a,
3936
        struct ggml_tensor  * b,
3937
0
        struct ggml_tensor  * c) {
3938
0
    GGML_ASSERT(a->ne[0] == b->ne[0]);
3939
0
    GGML_ASSERT(a->ne[2] == b->ne[2]);
3940
0
    GGML_ASSERT(a->ne[3] == b->ne[3]);
3941
0
    GGML_ASSERT(b->ne[1] == c->ne[0]);
3942
0
    GGML_ASSERT(b->ne[2] % c->ne[1] == 0);
3943
0
    GGML_ASSERT(b->ne[3] % c->ne[2] == 0);
3944
0
    GGML_ASSERT(c->ne[3] == 1);
3945
0
    GGML_ASSERT(b->type == GGML_TYPE_F32 || b->type == GGML_TYPE_F16);
3946
0
    GGML_ASSERT(c->type == GGML_TYPE_I64 || c->type == GGML_TYPE_I32);
3947
3948
0
    GGML_ASSERT(ggml_is_contiguous_rows(a));
3949
0
    GGML_ASSERT(ggml_is_contiguous_rows(b));
3950
3951
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
3952
3953
0
    result->op     = GGML_OP_SET_ROWS;
3954
0
    result->src[0] = b;
3955
0
    result->src[1] = c;
3956
0
    result->src[2] = a; // note: order is weird due to legacy reasons (https://github.com/ggml-org/llama.cpp/pull/16063#discussion_r2385795931)
3957
3958
0
    return result;
3959
0
}
3960
3961
// ggml_diag
3962
3963
struct ggml_tensor * ggml_diag(
3964
        struct ggml_context * ctx,
3965
0
        struct ggml_tensor  * a) {
3966
0
    GGML_ASSERT(a->ne[1] == 1);
3967
3968
0
    const int64_t ne[4] = { a->ne[0], a->ne[0], a->ne[2], a->ne[3] };
3969
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 4, ne);
3970
3971
0
    result->op     = GGML_OP_DIAG;
3972
0
    result->src[0] = a;
3973
3974
0
    return result;
3975
0
}
3976
3977
// ggml_diag_mask_inf
3978
3979
static struct ggml_tensor * ggml_diag_mask_inf_impl(
3980
        struct ggml_context * ctx,
3981
        struct ggml_tensor  * a,
3982
        int                   n_past,
3983
0
        bool                  inplace) {
3984
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
3985
3986
0
    int32_t params[] = { n_past };
3987
0
    ggml_set_op_params(result, params, sizeof(params));
3988
3989
0
    result->op     = GGML_OP_DIAG_MASK_INF;
3990
0
    result->src[0] = a;
3991
3992
0
    return result;
3993
0
}
3994
3995
struct ggml_tensor * ggml_diag_mask_inf(
3996
        struct ggml_context * ctx,
3997
        struct ggml_tensor  * a,
3998
0
        int                   n_past) {
3999
0
    return ggml_diag_mask_inf_impl(ctx, a, n_past, false);
4000
0
}
4001
4002
struct ggml_tensor * ggml_diag_mask_inf_inplace(
4003
        struct ggml_context * ctx,
4004
        struct ggml_tensor  * a,
4005
0
        int                   n_past) {
4006
0
    return ggml_diag_mask_inf_impl(ctx, a, n_past, true);
4007
0
}
4008
4009
// ggml_diag_mask_zero
4010
4011
static struct ggml_tensor * ggml_diag_mask_zero_impl(
4012
        struct ggml_context * ctx,
4013
        struct ggml_tensor  * a,
4014
        int                   n_past,
4015
0
        bool                  inplace) {
4016
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
4017
4018
0
    int32_t params[] = { n_past };
4019
0
    ggml_set_op_params(result, params, sizeof(params));
4020
4021
0
    result->op     = GGML_OP_DIAG_MASK_ZERO;
4022
0
    result->src[0] = a;
4023
4024
0
    return result;
4025
0
}
4026
4027
struct ggml_tensor * ggml_diag_mask_zero(
4028
        struct ggml_context * ctx,
4029
        struct ggml_tensor  * a,
4030
0
        int                   n_past) {
4031
0
    return ggml_diag_mask_zero_impl(ctx, a, n_past, false);
4032
0
}
4033
4034
struct ggml_tensor * ggml_diag_mask_zero_inplace(
4035
        struct ggml_context * ctx,
4036
        struct ggml_tensor  * a,
4037
0
        int                   n_past) {
4038
0
    return ggml_diag_mask_zero_impl(ctx, a, n_past, true);
4039
0
}
4040
4041
// ggml_soft_max
4042
4043
static struct ggml_tensor * ggml_soft_max_impl(
4044
        struct ggml_context * ctx,
4045
        struct ggml_tensor  * a,
4046
        struct ggml_tensor  * mask,
4047
        float                 scale,
4048
        float                 max_bias,
4049
0
        bool                  inplace) {
4050
0
    GGML_ASSERT(ggml_is_contiguous(a));
4051
4052
0
    if (mask) {
4053
0
        GGML_ASSERT(mask->type == GGML_TYPE_F16 || mask->type == GGML_TYPE_F32);
4054
0
        GGML_ASSERT(ggml_is_contiguous(mask));
4055
0
        GGML_ASSERT(mask->ne[0] == a->ne[0]);
4056
0
        GGML_ASSERT(mask->ne[1] >= a->ne[1]);
4057
0
        GGML_ASSERT(a->ne[2]%mask->ne[2] == 0);
4058
0
        GGML_ASSERT(a->ne[3]%mask->ne[3] == 0);
4059
0
    }
4060
4061
0
    if (max_bias > 0.0f) {
4062
0
        GGML_ASSERT(mask);
4063
0
    }
4064
4065
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
4066
4067
0
    float params[] = { scale, max_bias };
4068
0
    ggml_set_op_params(result, params, sizeof(params));
4069
4070
0
    result->op     = GGML_OP_SOFT_MAX;
4071
0
    result->src[0] = a;
4072
0
    result->src[1] = mask;
4073
4074
0
    return result;
4075
0
}
4076
4077
struct ggml_tensor * ggml_soft_max(
4078
        struct ggml_context * ctx,
4079
0
        struct ggml_tensor  * a) {
4080
0
    return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, false);
4081
0
}
4082
4083
struct ggml_tensor * ggml_soft_max_inplace(
4084
        struct ggml_context * ctx,
4085
0
        struct ggml_tensor  * a) {
4086
0
    return ggml_soft_max_impl(ctx, a, NULL, 1.0f, 0.0f, true);
4087
0
}
4088
4089
struct ggml_tensor * ggml_soft_max_ext(
4090
        struct ggml_context * ctx,
4091
        struct ggml_tensor  * a,
4092
        struct ggml_tensor  * mask,
4093
        float                 scale,
4094
0
        float                 max_bias) {
4095
0
    return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, false);
4096
0
}
4097
4098
struct ggml_tensor * ggml_soft_max_ext_inplace(
4099
        struct ggml_context * ctx,
4100
        struct ggml_tensor  * a,
4101
        struct ggml_tensor  * mask,
4102
        float                 scale,
4103
0
        float                 max_bias) {
4104
0
    return ggml_soft_max_impl(ctx, a, mask, scale, max_bias, true);
4105
0
}
4106
4107
void ggml_soft_max_add_sinks(
4108
        struct ggml_tensor * a,
4109
0
        struct ggml_tensor * sinks) {
4110
0
    if (!sinks) {
4111
0
        a->src[2] = NULL;
4112
0
        return;
4113
0
    }
4114
4115
0
    GGML_ASSERT(a->op == GGML_OP_SOFT_MAX);
4116
0
    GGML_ASSERT(a->src[2] == NULL);
4117
0
    GGML_ASSERT(a->src[0]->ne[2] == sinks->ne[0]);
4118
0
    GGML_ASSERT(sinks->type == GGML_TYPE_F32);
4119
4120
0
    a->src[2] = sinks;
4121
0
}
4122
4123
// ggml_soft_max_ext_back
4124
4125
static struct ggml_tensor * ggml_soft_max_ext_back_impl(
4126
        struct ggml_context * ctx,
4127
        struct ggml_tensor  * a,
4128
        struct ggml_tensor  * b,
4129
        float                 scale,
4130
        float                 max_bias,
4131
0
        bool                  inplace) {
4132
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
4133
4134
0
    result->op     = GGML_OP_SOFT_MAX_BACK;
4135
0
    result->src[0] = a;
4136
0
    result->src[1] = b;
4137
4138
0
    memcpy((float *) result->op_params + 0, &scale,    sizeof(float));
4139
0
    memcpy((float *) result->op_params + 1, &max_bias, sizeof(float));
4140
4141
0
    return result;
4142
0
}
4143
4144
struct ggml_tensor * ggml_soft_max_ext_back(
4145
        struct ggml_context * ctx,
4146
        struct ggml_tensor  * a,
4147
        struct ggml_tensor  * b,
4148
        float                 scale,
4149
0
        float                 max_bias) {
4150
0
    return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, false);
4151
0
}
4152
4153
struct ggml_tensor * ggml_soft_max_ext_back_inplace(
4154
        struct ggml_context * ctx,
4155
        struct ggml_tensor  * a,
4156
        struct ggml_tensor  * b,
4157
        float                 scale,
4158
0
        float                 max_bias) {
4159
0
    return ggml_soft_max_ext_back_impl(ctx, a, b, scale, max_bias, true);
4160
0
}
4161
4162
// ggml_rope
4163
4164
static struct ggml_tensor * ggml_rope_impl(
4165
        struct ggml_context * ctx,
4166
        struct ggml_tensor  * a,
4167
        struct ggml_tensor  * b,
4168
        struct ggml_tensor  * c,
4169
        int                   n_dims,
4170
        int                   sections[GGML_MROPE_SECTIONS],
4171
        int                   mode,
4172
        int                   n_ctx_orig,
4173
        float                 freq_base,
4174
        float                 freq_scale,
4175
        float                 ext_factor,
4176
        float                 attn_factor,
4177
        float                 beta_fast,
4178
        float                 beta_slow,
4179
0
        bool                  inplace) {
4180
0
    GGML_ASSERT((mode & 1) == 0 && "mode & 1 == 1 is no longer supported");
4181
4182
0
    GGML_ASSERT(ggml_is_vector(b));
4183
0
    GGML_ASSERT(b->type == GGML_TYPE_I32);
4184
4185
0
    bool mrope_used = mode & GGML_ROPE_TYPE_MROPE;
4186
0
    if (mrope_used) {
4187
0
        GGML_ASSERT(a->ne[2] * 4 == b->ne[0]); // mrope expecting 4 position ids per token
4188
0
    } else {
4189
0
        GGML_ASSERT(a->ne[2] == b->ne[0]);
4190
0
    }
4191
4192
0
    if (c) {
4193
0
        GGML_ASSERT(c->type == GGML_TYPE_F32);
4194
0
        GGML_ASSERT(c->ne[0] >= n_dims / 2);
4195
0
    }
4196
4197
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
4198
4199
0
    int32_t params[15] = { /*n_past*/ 0, n_dims, mode, /*n_ctx*/ 0, n_ctx_orig };
4200
0
    memcpy(params +  5, &freq_base,    sizeof(float));
4201
0
    memcpy(params +  6, &freq_scale,   sizeof(float));
4202
0
    memcpy(params +  7, &ext_factor,   sizeof(float));
4203
0
    memcpy(params +  8, &attn_factor,  sizeof(float));
4204
0
    memcpy(params +  9, &beta_fast,    sizeof(float));
4205
0
    memcpy(params + 10, &beta_slow,    sizeof(float));
4206
0
    if (mrope_used && sections) {
4207
0
        memcpy(params + 11, sections,  sizeof(int32_t) * GGML_MROPE_SECTIONS);
4208
0
    } else {
4209
0
        memset(params + 11, 0,         sizeof(int32_t) * GGML_MROPE_SECTIONS);
4210
0
    }
4211
0
    ggml_set_op_params(result, params, sizeof(params));
4212
4213
0
    result->op     = GGML_OP_ROPE;
4214
0
    result->src[0] = a;
4215
0
    result->src[1] = b;
4216
0
    result->src[2] = c;
4217
4218
0
    return result;
4219
0
}
4220
4221
struct ggml_tensor * ggml_rope(
4222
        struct ggml_context * ctx,
4223
        struct ggml_tensor  * a,
4224
        struct ggml_tensor  * b,
4225
        int                   n_dims,
4226
0
        int                   mode) {
4227
0
    return ggml_rope_impl(
4228
0
        ctx, a, b, NULL, n_dims, NULL, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, false
4229
0
    );
4230
0
}
4231
4232
struct ggml_tensor * ggml_rope_multi(
4233
        struct ggml_context * ctx,
4234
        struct ggml_tensor  * a,
4235
        struct ggml_tensor  * b,
4236
        struct ggml_tensor  * c,
4237
        int                   n_dims,
4238
        int                   sections[GGML_MROPE_SECTIONS],
4239
        int                   mode,
4240
        int                   n_ctx_orig,
4241
        float                 freq_base,
4242
        float                 freq_scale,
4243
        float                 ext_factor,
4244
        float                 attn_factor,
4245
        float                 beta_fast,
4246
0
        float                 beta_slow) {
4247
0
    return ggml_rope_impl(
4248
0
        ctx, a, b, c, n_dims, sections, mode, n_ctx_orig, freq_base, freq_scale,
4249
0
        ext_factor, attn_factor, beta_fast, beta_slow, false
4250
0
    );
4251
0
}
4252
4253
struct ggml_tensor * ggml_rope_multi_inplace(
4254
        struct ggml_context * ctx,
4255
        struct ggml_tensor  * a,
4256
        struct ggml_tensor  * b,
4257
        struct ggml_tensor  * c,
4258
        int                   n_dims,
4259
        int                   sections[GGML_MROPE_SECTIONS],
4260
        int                   mode,
4261
        int                   n_ctx_orig,
4262
        float                 freq_base,
4263
        float                 freq_scale,
4264
        float                 ext_factor,
4265
        float                 attn_factor,
4266
        float                 beta_fast,
4267
0
        float                 beta_slow) {
4268
0
    return ggml_rope_impl(
4269
0
        ctx, a, b, c, n_dims, sections, mode, n_ctx_orig, freq_base, freq_scale,
4270
0
        ext_factor, attn_factor, beta_fast, beta_slow, true
4271
0
    );
4272
0
}
4273
4274
struct ggml_tensor * ggml_rope_inplace(
4275
        struct ggml_context * ctx,
4276
        struct ggml_tensor  * a,
4277
        struct ggml_tensor  * b,
4278
        int                   n_dims,
4279
0
        int                   mode) {
4280
0
    return ggml_rope_impl(
4281
0
        ctx, a, b, NULL, n_dims, NULL, mode, 0, 10000.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, true
4282
0
    );
4283
0
}
4284
4285
struct ggml_tensor * ggml_rope_ext(
4286
        struct ggml_context * ctx,
4287
        struct ggml_tensor  * a,
4288
        struct ggml_tensor  * b,
4289
        struct ggml_tensor  * c,
4290
        int                   n_dims,
4291
        int                   mode,
4292
        int                   n_ctx_orig,
4293
        float                 freq_base,
4294
        float                 freq_scale,
4295
        float                 ext_factor,
4296
        float                 attn_factor,
4297
        float                 beta_fast,
4298
0
        float                 beta_slow) {
4299
0
    return ggml_rope_impl(
4300
0
        ctx, a, b, c, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale,
4301
0
        ext_factor, attn_factor, beta_fast, beta_slow, false
4302
0
    );
4303
0
}
4304
4305
struct ggml_tensor * ggml_rope_ext_inplace(
4306
        struct ggml_context * ctx,
4307
        struct ggml_tensor  * a,
4308
        struct ggml_tensor  * b,
4309
        struct ggml_tensor  * c,
4310
        int                   n_dims,
4311
        int                   mode,
4312
        int                   n_ctx_orig,
4313
        float                 freq_base,
4314
        float                 freq_scale,
4315
        float                 ext_factor,
4316
        float                 attn_factor,
4317
        float                 beta_fast,
4318
0
        float                 beta_slow) {
4319
0
    return ggml_rope_impl(
4320
0
        ctx, a, b, c, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale,
4321
0
        ext_factor, attn_factor, beta_fast, beta_slow, true
4322
0
    );
4323
0
}
4324
4325
struct ggml_tensor * ggml_rope_custom(
4326
        struct ggml_context * ctx,
4327
        struct ggml_tensor  * a,
4328
        struct ggml_tensor  * b,
4329
        int                   n_dims,
4330
        int                   mode,
4331
        int                   n_ctx_orig,
4332
        float                 freq_base,
4333
        float                 freq_scale,
4334
        float                 ext_factor,
4335
        float                 attn_factor,
4336
        float                 beta_fast,
4337
0
        float                 beta_slow) {
4338
0
    return ggml_rope_impl(
4339
0
        ctx, a, b, NULL, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale,
4340
0
        ext_factor, attn_factor, beta_fast, beta_slow, false
4341
0
    );
4342
0
}
4343
4344
struct ggml_tensor * ggml_rope_custom_inplace(
4345
        struct ggml_context * ctx,
4346
        struct ggml_tensor  * a,
4347
        struct ggml_tensor  * b,
4348
        int                   n_dims,
4349
        int                   mode,
4350
        int                   n_ctx_orig,
4351
        float                 freq_base,
4352
        float                 freq_scale,
4353
        float                 ext_factor,
4354
        float                 attn_factor,
4355
        float                 beta_fast,
4356
0
        float                 beta_slow) {
4357
0
    return ggml_rope_impl(
4358
0
        ctx, a, b, NULL, n_dims, NULL, mode, n_ctx_orig, freq_base, freq_scale,
4359
0
        ext_factor, attn_factor, beta_fast, beta_slow, true
4360
0
    );
4361
0
}
4362
4363
// Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get
4364
// `corr_dim(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))`
4365
0
static float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
4366
0
    return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float)M_PI)) / (2 * logf(base));
4367
0
}
4368
4369
void ggml_rope_yarn_corr_dims(
4370
    int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2]
4371
0
) {
4372
    // start and end correction dims
4373
0
    float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
4374
0
    float end   =  ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
4375
0
    dims[0] = MAX(0, start);
4376
0
    dims[1] = MIN(n_dims - 1, end);
4377
0
}
4378
4379
// ggml_rope_back
4380
4381
struct ggml_tensor * ggml_rope_ext_back(
4382
        struct ggml_context * ctx,
4383
        struct ggml_tensor  * a,
4384
        struct ggml_tensor  * b,
4385
        struct ggml_tensor  * c,
4386
        int                   n_dims,
4387
        int                   mode,
4388
        int                   n_ctx_orig,
4389
        float                 freq_base,
4390
        float                 freq_scale,
4391
        float                 ext_factor,
4392
        float                 attn_factor,
4393
        float                 beta_fast,
4394
0
        float                 beta_slow) {
4395
0
    struct ggml_tensor * result = ggml_rope_ext(
4396
0
        ctx, a, b, c, n_dims, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
4397
0
    result->op = GGML_OP_ROPE_BACK;
4398
0
    return result;
4399
0
}
4400
4401
struct ggml_tensor * ggml_rope_multi_back(
4402
        struct ggml_context * ctx,
4403
        struct ggml_tensor  * a,
4404
        struct ggml_tensor  * b,
4405
        struct ggml_tensor  * c,
4406
        int                   n_dims,
4407
        int                   sections[4],
4408
        int                   mode,
4409
        int                   n_ctx_orig,
4410
        float                 freq_base,
4411
        float                 freq_scale,
4412
        float                 ext_factor,
4413
        float                 attn_factor,
4414
        float                 beta_fast,
4415
0
        float                 beta_slow) {
4416
0
    struct ggml_tensor * result = ggml_rope_multi(
4417
0
        ctx, a, b, c, n_dims, sections, mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
4418
0
    result->op = GGML_OP_ROPE_BACK;
4419
0
    return result;
4420
0
}
4421
// ggml_clamp
4422
4423
struct ggml_tensor * ggml_clamp(
4424
        struct ggml_context * ctx,
4425
        struct ggml_tensor  * a,
4426
        float                 min,
4427
0
        float                 max) {
4428
    // TODO: when implement backward, fix this:
4429
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
4430
4431
0
    float params[] = { min, max };
4432
0
    ggml_set_op_params(result, params, sizeof(params));
4433
4434
0
    result->op     = GGML_OP_CLAMP;
4435
0
    result->src[0] = a;
4436
4437
0
    return result;
4438
0
}
4439
4440
0
static int64_t ggml_calc_conv_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
4441
0
    return (ins + 2 * p - d * (ks - 1) - 1) / s + 1;
4442
0
}
4443
4444
// im2col: [N, IC, IH, IW] => [N, OH, OW, IC*KH*KW]
4445
// a: [OC,IC, KH, KW]
4446
// b: [N, IC, IH, IW]
4447
// result: [N, OH, OW, IC*KH*KW]
4448
struct ggml_tensor * ggml_im2col(
4449
        struct ggml_context * ctx,
4450
        struct ggml_tensor  * a,
4451
        struct ggml_tensor  * b,
4452
        int                   s0,
4453
        int                   s1,
4454
        int                   p0,
4455
        int                   p1,
4456
        int                   d0,
4457
        int                   d1,
4458
        bool                  is_2D,
4459
0
        enum ggml_type        dst_type) {
4460
0
    if (is_2D) {
4461
0
        GGML_ASSERT(a->ne[2] == b->ne[2]);
4462
0
    } else {
4463
        //GGML_ASSERT(b->ne[1] % a->ne[1] == 0);
4464
0
        GGML_ASSERT(b->ne[1] == a->ne[1]);
4465
0
        GGML_ASSERT(b->ne[3] == 1);
4466
0
    }
4467
4468
0
    const int64_t OH = is_2D ? ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1) : 0;
4469
0
    const int64_t OW =         ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
4470
4471
0
    GGML_ASSERT((!is_2D || OH > 0) && "b too small compared to a");
4472
0
    GGML_ASSERT((OW > 0)           && "b too small compared to a");
4473
4474
0
    const int64_t ne[4] = {
4475
0
        is_2D ? (a->ne[2] * a->ne[1] * a->ne[0]) : a->ne[1] * a->ne[0],
4476
0
        OW,
4477
0
        is_2D ? OH : b->ne[2],
4478
0
        is_2D ?      b->ne[3] : 1,
4479
0
    };
4480
4481
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
4482
0
    int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
4483
0
    ggml_set_op_params(result, params, sizeof(params));
4484
4485
0
    result->op     = GGML_OP_IM2COL;
4486
0
    result->src[0] = a;
4487
0
    result->src[1] = b;
4488
4489
0
    return result;
4490
0
}
4491
4492
struct ggml_tensor * ggml_im2col_back(
4493
        struct ggml_context * ctx,
4494
        struct ggml_tensor  * a,
4495
        struct ggml_tensor  * b,
4496
        int64_t             * ne,
4497
        int                   s0,
4498
        int                   s1,
4499
        int                   p0,
4500
        int                   p1,
4501
        int                   d0,
4502
        int                   d1,
4503
0
        bool                  is_2D) {
4504
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
4505
0
    int32_t params[] = { s0, s1, p0, p1, d0, d1, (is_2D ? 1 : 0) };
4506
0
    ggml_set_op_params(result, params, sizeof(params));
4507
4508
0
    result->op     = GGML_OP_IM2COL_BACK;
4509
0
    result->src[0] = a;
4510
0
    result->src[1] = b;
4511
4512
0
    return result;
4513
0
}
4514
4515
// ggml_conv_1d
4516
4517
struct ggml_tensor * ggml_conv_1d(
4518
        struct ggml_context * ctx,
4519
        struct ggml_tensor  * a,
4520
        struct ggml_tensor  * b,
4521
        int                   s0,
4522
        int                   p0,
4523
0
        int                   d0) {
4524
0
    struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, 0, p0, 0, d0, 0, false, a->type == GGML_TYPE_BF16 ? GGML_TYPE_F32 : GGML_TYPE_F16); // [N, OL, IC * K]
4525
4526
0
    struct ggml_tensor * result =
4527
0
        ggml_mul_mat(ctx,
4528
0
                ggml_reshape_2d(ctx, im2col, im2col->ne[0], (im2col->ne[2] * im2col->ne[1])), // [N, OL, IC * K] => [N*OL, IC * K]
4529
0
                ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1]), a->ne[2]));                    // [OC,IC, K] => [OC, IC * K]
4530
4531
0
    result = ggml_reshape_3d(ctx, result, im2col->ne[1], a->ne[2], im2col->ne[2]); // [N, OC, OL]
4532
4533
0
    return result;
4534
0
}
4535
4536
// ggml_conv_1d_ph
4537
4538
struct ggml_tensor* ggml_conv_1d_ph(
4539
        struct ggml_context * ctx,
4540
        struct ggml_tensor  * a,
4541
        struct ggml_tensor  * b,
4542
        int                   s,
4543
0
        int                   d) {
4544
0
    return ggml_conv_1d(ctx, a, b, s, a->ne[0] / 2, d);
4545
0
}
4546
4547
// ggml_conv_1d_dw
4548
4549
struct ggml_tensor * ggml_conv_1d_dw(
4550
        struct ggml_context * ctx,
4551
        struct ggml_tensor  * a,
4552
        struct ggml_tensor  * b,
4553
        int                   s0,
4554
        int                   p0,
4555
0
        int                   d0) {
4556
0
    struct ggml_tensor * new_b = ggml_reshape_4d(ctx, b, b->ne[0], 1, b->ne[1], b->ne[2]);
4557
4558
0
    struct ggml_tensor * im2col = ggml_im2col(ctx, a, new_b, s0, 0, p0, 0, d0, 0, false, a->type == GGML_TYPE_BF16 ? GGML_TYPE_F32 : GGML_TYPE_F16);
4559
4560
0
    struct ggml_tensor * result = ggml_mul_mat(ctx, im2col, a);
4561
4562
0
    result = ggml_reshape_3d(ctx, result, result->ne[0], result->ne[2], 1);
4563
4564
0
    return result;
4565
0
}
4566
4567
// ggml_conv_1d_dw_ph
4568
4569
struct ggml_tensor * ggml_conv_1d_dw_ph(
4570
        struct ggml_context * ctx,
4571
        struct ggml_tensor  * a,
4572
        struct ggml_tensor  * b,
4573
        int                   s0,
4574
0
        int                   d0) {
4575
0
    return ggml_conv_1d_dw(ctx, a, b, s0, a->ne[0] / 2, d0);
4576
0
}
4577
4578
// ggml_col2im_1d
4579
4580
struct ggml_tensor * ggml_col2im_1d(
4581
        struct ggml_context * ctx,
4582
        struct ggml_tensor  * a,
4583
        int                   s0,
4584
        int                   oc,
4585
0
        int                   p0) {
4586
0
    GGML_ASSERT(ggml_is_matrix(a));
4587
0
    GGML_ASSERT(ggml_is_contiguous(a));
4588
0
    GGML_ASSERT(a->type == GGML_TYPE_F32 || a->type == GGML_TYPE_F16 || a->type == GGML_TYPE_BF16);
4589
0
    GGML_ASSERT(s0 > 0);
4590
0
    GGML_ASSERT(oc > 0);
4591
0
    GGML_ASSERT(p0 >= 0);
4592
4593
0
    const int64_t K_OC = a->ne[0];
4594
0
    const int64_t T_in = a->ne[1];
4595
0
    const int64_t K = K_OC / oc;
4596
0
    const int64_t T_out = (T_in - 1) * s0 + K - 2 * p0;
4597
4598
0
    GGML_ASSERT(K_OC == K * oc);  // a->ne[0] must be a whole number of oc blocks
4599
0
    GGML_ASSERT(K > 0 && T_out > 0);
4600
4601
0
    const int64_t ne[4] = { T_out, oc, 1, 1 };
4602
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, a->type, 2, ne);
4603
4604
0
    int32_t params[] = { s0, (int32_t)oc, (int32_t)p0 };
4605
0
    ggml_set_op_params(result, params, sizeof(params));
4606
4607
0
    result->op     = GGML_OP_COL2IM_1D;
4608
0
    result->src[0] = a;
4609
4610
0
    return result;
4611
0
}
4612
4613
// ggml_conv_transpose_1d
4614
4615
0
static int64_t ggml_calc_conv_transpose_1d_output_size(int64_t ins, int64_t ks, int s, int p, int d) {
4616
0
    return (ins - 1) * s - 2 * p + d * (ks - 1) + 1;
4617
0
}
4618
4619
GGML_API struct ggml_tensor * ggml_conv_transpose_1d(
4620
        struct ggml_context * ctx,
4621
        struct ggml_tensor  * a,
4622
        struct ggml_tensor  * b,
4623
        int                   s0,
4624
        int                   p0,
4625
0
        int                   d0) {
4626
0
    GGML_ASSERT(ggml_is_matrix(b));
4627
0
    GGML_ASSERT(a->ne[2] == b->ne[1]);
4628
0
    GGML_ASSERT(a->ne[3] == 1);
4629
4630
0
    GGML_ASSERT(p0 == 0);
4631
0
    GGML_ASSERT(d0 == 1);
4632
4633
0
    const int64_t ne[4] = {
4634
0
        ggml_calc_conv_transpose_1d_output_size(b->ne[0], a->ne[0], s0, 0 /*p0*/, 1 /*d0*/),
4635
0
        a->ne[1], b->ne[2], 1,
4636
0
    };
4637
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
4638
4639
0
    int32_t params[] = { s0, p0, d0 };
4640
0
    ggml_set_op_params(result, params, sizeof(params));
4641
4642
0
    result->op     = GGML_OP_CONV_TRANSPOSE_1D;
4643
0
    result->src[0] = a;
4644
0
    result->src[1] = b;
4645
4646
0
    return result;
4647
0
}
4648
4649
// ggml_conv_2d
4650
4651
// a: [OC,IC, KH, KW]
4652
// b: [N, IC, IH, IW]
4653
// result: [N, OC, OH, OW]
4654
struct ggml_tensor * ggml_conv_2d(
4655
        struct ggml_context * ctx,
4656
        struct ggml_tensor  * a,
4657
        struct ggml_tensor  * b,
4658
        int                   s0,
4659
        int                   s1,
4660
        int                   p0,
4661
        int                   p1,
4662
        int                   d0,
4663
0
        int                   d1) {
4664
0
    struct ggml_tensor * im2col = ggml_im2col(ctx, a, b, s0, s1, p0, p1, d0, d1, true, a->type == GGML_TYPE_BF16 ? GGML_TYPE_F32 : GGML_TYPE_F16); // [N, OH, OW, IC * KH * KW]
4665
4666
0
    struct ggml_tensor * result =
4667
0
        ggml_mul_mat(ctx,
4668
0
                ggml_reshape_2d(ctx, im2col, im2col->ne[0],  im2col->ne[3] * im2col->ne[2] * im2col->ne[1]), // [N, OH, OW, IC * KH * KW] => [N*OH*OW, IC * KH * KW]
4669
0
                ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1] * a->ne[2]),  a->ne[3]));                       // [OC,IC, KH, KW] => [OC, IC * KH * KW]
4670
4671
0
    result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], im2col->ne[3], a->ne[3]); // [OC, N, OH, OW]
4672
0
    result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OH, OW]
4673
4674
4675
0
    return result;
4676
0
}
4677
4678
// a: [OC*IC, KD, KH, KW]
4679
// b: [N*IC, ID, IH, IW]
4680
// result: [N*OD, OH, OW, IC * KD * KH * KW]
4681
struct ggml_tensor * ggml_im2col_3d(
4682
        struct ggml_context * ctx,
4683
        struct ggml_tensor  * a,
4684
        struct ggml_tensor  * b,
4685
        int64_t               IC,
4686
        int                   s0, // stride width
4687
        int                   s1, // stride height
4688
        int                   s2, // stride depth
4689
        int                   p0, // padding width
4690
        int                   p1, // padding height
4691
        int                   p2, // padding depth
4692
        int                   d0, // dilation width
4693
        int                   d1, // dilation height
4694
        int                   d2, // dilation depth
4695
0
        enum ggml_type        dst_type) {
4696
0
    const int64_t N = b->ne[3] / IC;
4697
0
    const int64_t ID = b->ne[2];
4698
0
    const int64_t IH = b->ne[1];
4699
0
    const int64_t IW = b->ne[0];
4700
4701
0
    const int64_t OC = a->ne[3] / IC;
4702
0
    UNUSED(OC);
4703
0
    const int64_t KD = a->ne[2];
4704
0
    const int64_t KH = a->ne[1];
4705
0
    const int64_t KW = a->ne[0];
4706
0
    const int64_t OD = ggml_calc_conv_output_size(ID, KD, s2, p2, d2);
4707
0
    const int64_t OH = ggml_calc_conv_output_size(IH, KH, s1, p1, d1);
4708
0
    const int64_t OW = ggml_calc_conv_output_size(IW, KW, s0, p0, d0);
4709
4710
0
    GGML_ASSERT((OD > 0)  && "b too small compared to a");
4711
0
    GGML_ASSERT((OH > 0)  && "b too small compared to a");
4712
0
    GGML_ASSERT((OW > 0)  && "b too small compared to a");
4713
4714
4715
0
    const int64_t ne[4] = {KW*KH*KD*IC, OW, OH, OD*N};
4716
4717
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, dst_type, 4, ne);
4718
0
    int32_t params[] = { s0, s1, s2, p0, p1, p2, d0, d1, d2, (int32_t)IC};
4719
0
    ggml_set_op_params(result, params, sizeof(params));
4720
4721
0
    result->op     = GGML_OP_IM2COL_3D;
4722
0
    result->src[0] = a;
4723
0
    result->src[1] = b;
4724
4725
0
    return result;
4726
0
}
4727
4728
// a: [OC*IC, KD, KH, KW]
4729
// b: [N*IC, ID, IH, IW]
4730
// result: [N*OC, OD, OH, OW]
4731
struct ggml_tensor * ggml_conv_3d(
4732
        struct ggml_context * ctx,
4733
        struct ggml_tensor  * a,
4734
        struct ggml_tensor  * b,
4735
        int64_t               IC,
4736
        int                   s0, // stride width
4737
        int                   s1, // stride height
4738
        int                   s2, // stride depth
4739
        int                   p0, // padding width
4740
        int                   p1, // padding height
4741
        int                   p2, // padding depth
4742
        int                   d0, // dilation width
4743
        int                   d1, // dilation height
4744
        int                   d2  // dilation depth
4745
0
        ) {
4746
0
    struct ggml_tensor * im2col = ggml_im2col_3d(ctx, a, b, IC, s0, s1, s2, p0, p1, p2, d0, d1, d2, a->type == GGML_TYPE_BF16 ? GGML_TYPE_F32 : GGML_TYPE_F16); // [N*OD, OH, OW, IC * KD * KH * KW]
4747
4748
0
    int64_t OC = a->ne[3] / IC;
4749
0
    int64_t N = b->ne[3] / IC;
4750
0
    struct ggml_tensor * result =
4751
0
        ggml_mul_mat(ctx,
4752
0
                ggml_reshape_2d(ctx, im2col, im2col->ne[0], im2col->ne[3] * im2col->ne[2] * im2col->ne[1]), // [N*OD, OH, OW, IC * KD * KH * KW] => [N*OD*OH*OW, IC * KD * KH * KW]
4753
0
                ggml_reshape_2d(ctx, a, (a->ne[0] * a->ne[1] * a->ne[2] * IC), OC));                          // [OC*IC, KD, KH, KW] => [OC, IC * KD * KH * KW]
4754
4755
0
    int64_t OD = im2col->ne[3] / N;
4756
0
    result = ggml_reshape_4d(ctx, result, im2col->ne[1]*im2col->ne[2], OD, N, OC); // [OC, N*OD*OH*OW] => [OC, N, OD, OH*OW]
4757
0
    result = ggml_cont(ctx, ggml_permute(ctx, result, 0, 1, 3, 2)); // [N, OC, OD, OH*OW]
4758
0
    result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], OD, OC * N); // [N*OC, OD, OH, OW]
4759
4760
0
    return result;
4761
0
}
4762
4763
// ggml_conv_2d_sk_p0
4764
4765
struct ggml_tensor * ggml_conv_2d_sk_p0(
4766
        struct ggml_context * ctx,
4767
        struct ggml_tensor  * a,
4768
0
        struct ggml_tensor  * b) {
4769
0
    return ggml_conv_2d(ctx, a, b, a->ne[0], a->ne[1], 0, 0, 1, 1);
4770
0
}
4771
4772
// ggml_conv_2d_s1_ph
4773
4774
struct ggml_tensor * ggml_conv_2d_s1_ph(
4775
        struct ggml_context * ctx,
4776
        struct ggml_tensor  * a,
4777
0
        struct ggml_tensor  * b) {
4778
0
    return ggml_conv_2d(ctx, a, b, 1, 1, a->ne[0] / 2, a->ne[1] / 2, 1, 1);
4779
0
}
4780
4781
// ggml_conv_2d_dw
4782
4783
struct ggml_tensor * ggml_conv_2d_dw(
4784
        struct ggml_context * ctx,
4785
        struct ggml_tensor  * a,
4786
        struct ggml_tensor  * b,
4787
        int                   s0,
4788
        int                   s1,
4789
        int                   p0,
4790
        int                   p1,
4791
        int                   d0,
4792
0
        int                   d1) {
4793
0
    struct ggml_tensor * new_a = ggml_reshape_4d(ctx, a, a->ne[0], a->ne[1], 1, a->ne[2] * a->ne[3]);
4794
0
    struct ggml_tensor * im2col = ggml_im2col(ctx, new_a,
4795
0
                                        ggml_reshape_4d(ctx, b, b->ne[0], b->ne[1], 1, b->ne[2] * b->ne[3]),
4796
0
                                        s0, s1, p0, p1, d0, d1, true, a->type == GGML_TYPE_BF16 ? GGML_TYPE_F32 : GGML_TYPE_F16); // [N * IC, OH, OW, KH * KW]
4797
0
    struct ggml_tensor * new_b = ggml_reshape_4d(ctx, im2col, im2col->ne[0], im2col->ne[2] * im2col->ne[1], b->ne[2], b->ne[3]); // [N * IC, OH, OW, KH * KW] => [N, IC, OH * OW, KH * KW]
4798
4799
0
    new_a = ggml_reshape_4d(ctx, new_a, (new_a->ne[0] * new_a->ne[1]), new_a->ne[2],  new_a->ne[3], 1);                       // [OC,1, KH, KW] => [1, OC, 1, KH * KW]
4800
0
    struct ggml_tensor * result = ggml_mul_mat(ctx, new_a, new_b);
4801
0
    result = ggml_reshape_4d(ctx, result, im2col->ne[1], im2col->ne[2], b->ne[2], b->ne[3]); // [N, OC, OH, OW]
4802
4803
0
    return result;
4804
0
}
4805
4806
// ggml_conv_2d_dw_direct
4807
4808
struct ggml_tensor * ggml_conv_2d_dw_direct(
4809
        struct ggml_context * ctx,
4810
        struct ggml_tensor  * a,
4811
        struct ggml_tensor  * b,
4812
        int                   stride0,
4813
        int                   stride1,
4814
        int                   pad0,
4815
        int                   pad1,
4816
        int                   dilation0,
4817
0
        int                   dilation1) {
4818
0
    GGML_ASSERT(a->ne[2] == 1);
4819
0
    GGML_ASSERT(a->ne[3] == b->ne[2]);
4820
0
    int64_t ne[4];
4821
0
    ne[0] = ggml_calc_conv_output_size(b->ne[0], a->ne[0], stride0, pad0, dilation0);
4822
0
    ne[1] = ggml_calc_conv_output_size(b->ne[1], a->ne[1], stride1, pad1, dilation1);
4823
0
    ne[2] = b->ne[2];
4824
0
    ne[3] = b->ne[3];
4825
4826
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, b->type, 4, ne);
4827
4828
0
    if (ggml_is_contiguous_channels(b)) {
4829
        // Result will be permuted the same way as input (CWHN order)
4830
0
        const int64_t type_size = ggml_type_size(result->type);
4831
0
        GGML_ASSERT(ggml_blck_size(result->type) == 1);
4832
0
        result->nb[0] = result->ne[2] * type_size;
4833
0
        result->nb[1] = result->ne[0] * result->nb[0];
4834
0
        result->nb[2] = type_size;
4835
0
    }
4836
4837
0
    int32_t params[] = { stride0, stride1, pad0, pad1, dilation0, dilation1 };
4838
0
    ggml_set_op_params(result, params, sizeof(params));
4839
4840
0
    result->op     = GGML_OP_CONV_2D_DW;
4841
0
    result->src[0] = a;
4842
0
    result->src[1] = b;
4843
0
    return result;
4844
0
}
4845
4846
// ggml_conv_2d_direct
4847
4848
struct ggml_tensor * ggml_conv_2d_direct(
4849
        struct ggml_context * ctx,
4850
        struct ggml_tensor  * a,   // convolution kernel [KW, KH, IC, OC]
4851
        struct ggml_tensor  * b,   // input data [W, H, C, N]
4852
        int                   s0,  // stride dimension 0
4853
        int                   s1,  // stride dimension 1
4854
        int                   p0,  // padding dimension 0
4855
        int                   p1,  // padding dimension 1
4856
        int                   d0,  // dilation dimension 0
4857
0
        int                   d1) {// dilation dimension 1
4858
4859
0
    GGML_ASSERT(a->ne[2] == b->ne[2]);
4860
    //GGML_ASSERT(a->type == b->type);
4861
4862
0
    int64_t ne[4];
4863
0
    ne[0] = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
4864
0
    ne[1] = ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1);
4865
0
    ne[2] = a->ne[3];
4866
0
    ne[3] = b->ne[3];
4867
4868
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, b->type, 4, ne);
4869
4870
0
    ggml_set_op_params_i32(result, 0, s0);
4871
0
    ggml_set_op_params_i32(result, 1, s1);
4872
0
    ggml_set_op_params_i32(result, 2, p0);
4873
0
    ggml_set_op_params_i32(result, 3, p1);
4874
0
    ggml_set_op_params_i32(result, 4, d0);
4875
0
    ggml_set_op_params_i32(result, 5, d1);
4876
4877
0
    result->op = GGML_OP_CONV_2D;
4878
0
    result->src[0] = a;
4879
0
    result->src[1] = b;
4880
4881
0
    return result;
4882
0
}
4883
4884
// ggml_conv_3d_direct
4885
4886
struct ggml_tensor * ggml_conv_3d_direct(
4887
        struct ggml_context * ctx,
4888
        struct ggml_tensor  * a,
4889
        struct ggml_tensor  * b,
4890
        int                   s0,
4891
        int                   s1,
4892
        int                   s2,
4893
        int                   p0,
4894
        int                   p1,
4895
        int                   p2,
4896
        int                   d0,
4897
        int                   d1,
4898
        int                   d2,
4899
        int                   c,
4900
        int                   n,
4901
0
        int                   oc) {
4902
4903
0
    GGML_ASSERT(a->ne[3] == (int64_t) c * oc);
4904
0
    GGML_ASSERT(b->ne[3] == (int64_t) c * n);
4905
4906
0
    int64_t ne[4];
4907
0
    ne[0] = ggml_calc_conv_output_size(b->ne[0], a->ne[0], s0, p0, d0);
4908
0
    ne[1] = ggml_calc_conv_output_size(b->ne[1], a->ne[1], s1, p1, d1);
4909
0
    ne[2] = ggml_calc_conv_output_size(b->ne[2], a->ne[2], s2, p2, d2);
4910
0
    ne[3] = (int64_t) oc * n;
4911
4912
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
4913
4914
0
    ggml_set_op_params_i32(result, 0,  s0);
4915
0
    ggml_set_op_params_i32(result, 1,  s1);
4916
0
    ggml_set_op_params_i32(result, 2,  s2);
4917
0
    ggml_set_op_params_i32(result, 3,  p0);
4918
0
    ggml_set_op_params_i32(result, 4,  p1);
4919
0
    ggml_set_op_params_i32(result, 5,  p2);
4920
0
    ggml_set_op_params_i32(result, 6,  d0);
4921
0
    ggml_set_op_params_i32(result, 7,  d1);
4922
0
    ggml_set_op_params_i32(result, 8,  d2);
4923
0
    ggml_set_op_params_i32(result, 9,  c);
4924
0
    ggml_set_op_params_i32(result, 10, n);
4925
0
    ggml_set_op_params_i32(result, 11, oc);
4926
4927
0
    result->op = GGML_OP_CONV_3D;
4928
0
    result->src[0] = a;
4929
0
    result->src[1] = b;
4930
4931
0
    return result;
4932
0
}
4933
4934
// ggml_conv_transpose_2d_p0
4935
4936
0
static int64_t ggml_calc_conv_transpose_output_size(int64_t ins, int64_t ks, int s, int p) {
4937
0
    return (ins - 1) * s - 2 * p + ks;
4938
0
}
4939
4940
struct ggml_tensor * ggml_conv_transpose_2d_p0(
4941
        struct ggml_context * ctx,
4942
        struct ggml_tensor  * a,
4943
        struct ggml_tensor  * b,
4944
0
        int                   stride) {
4945
0
    GGML_ASSERT(a->ne[3] == b->ne[2]);
4946
4947
0
    const int64_t ne[4] = {
4948
0
        ggml_calc_conv_transpose_output_size(b->ne[0], a->ne[0], stride, 0 /*p0*/),
4949
0
        ggml_calc_conv_transpose_output_size(b->ne[1], a->ne[1], stride, 0 /*p1*/),
4950
0
        a->ne[2], b->ne[3],
4951
0
    };
4952
4953
0
    struct ggml_tensor* result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
4954
4955
0
    ggml_set_op_params_i32(result, 0, stride);
4956
4957
0
    result->op     = GGML_OP_CONV_TRANSPOSE_2D;
4958
0
    result->src[0] = a;
4959
0
    result->src[1] = b;
4960
4961
0
    return result;
4962
0
}
4963
4964
// ggml_pool_*
4965
4966
0
static int64_t ggml_calc_pool_output_size(int64_t ins, int ks, int s, float p) {
4967
0
    return (ins + 2 * p - ks) / s + 1;
4968
0
}
4969
4970
// ggml_pool_1d
4971
4972
struct ggml_tensor * ggml_pool_1d(
4973
        struct ggml_context * ctx,
4974
        struct ggml_tensor  * a,
4975
        enum ggml_op_pool     op,
4976
        int                   k0,
4977
        int                   s0,
4978
0
        int                   p0) {
4979
0
    const int64_t ne[4] = {
4980
0
        ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
4981
0
        a->ne[1],
4982
0
        a->ne[2],
4983
0
        a->ne[3],
4984
0
    };
4985
0
    GGML_ASSERT(ne[0] > 0);
4986
4987
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
4988
4989
0
    int32_t params[] = { op, k0, s0, p0 };
4990
0
    ggml_set_op_params(result, params, sizeof(params));
4991
4992
0
    result->op     = GGML_OP_POOL_1D;
4993
0
    result->src[0] = a;
4994
4995
0
    return result;
4996
0
}
4997
4998
// ggml_pool_2d
4999
5000
struct ggml_tensor * ggml_pool_2d(
5001
        struct ggml_context * ctx,
5002
        struct ggml_tensor  * a,
5003
        enum ggml_op_pool     op,
5004
        int                   k0,
5005
        int                   k1,
5006
        int                   s0,
5007
        int                   s1,
5008
        float                 p0,
5009
0
        float                 p1) {
5010
0
    struct ggml_tensor * result;
5011
0
    const int64_t ne[4] = {
5012
0
        ggml_calc_pool_output_size(a->ne[0], k0, s0, p0),
5013
0
        ggml_calc_pool_output_size(a->ne[1], k1, s1, p1),
5014
0
        a->ne[2],
5015
0
        a->ne[3],
5016
0
    };
5017
0
    GGML_ASSERT(ne[0] > 0);
5018
0
    GGML_ASSERT(ne[1] > 0);
5019
5020
0
    result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5021
5022
0
    int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
5023
0
    ggml_set_op_params(result, params, sizeof(params));
5024
5025
0
    result->op     = GGML_OP_POOL_2D;
5026
0
    result->src[0] = a;
5027
5028
0
    return result;
5029
0
}
5030
5031
struct ggml_tensor * ggml_pool_2d_back(
5032
        struct ggml_context * ctx,
5033
        struct ggml_tensor  * a,
5034
        struct ggml_tensor  * af,
5035
        enum ggml_op_pool     op,
5036
        int                   k0,
5037
        int                   k1,
5038
        int                   s0,
5039
        int                   s1,
5040
        float                 p0,
5041
0
        float                 p1) {
5042
0
    struct ggml_tensor * result;
5043
0
    result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, af->ne);
5044
5045
0
    int32_t params[] = { op, k0, k1, s0, s1, p0, p1 };
5046
0
    ggml_set_op_params(result, params, sizeof(params));
5047
5048
0
    result->op     = GGML_OP_POOL_2D_BACK;
5049
0
    result->src[0] = a;
5050
0
    result->src[1] = af;
5051
5052
0
    return result;
5053
0
}
5054
5055
// ggml_upscale / ggml_interpolate
5056
5057
static struct ggml_tensor * ggml_interpolate_impl(
5058
        struct ggml_context * ctx,
5059
        struct ggml_tensor  * a,
5060
        int64_t               ne0,
5061
        int64_t               ne1,
5062
        int64_t               ne2,
5063
        int64_t               ne3,
5064
0
        uint32_t              mode) {
5065
0
    GGML_ASSERT((mode & 0xFF) < GGML_SCALE_MODE_COUNT);
5066
    // TODO: implement antialias for modes other than bilinear
5067
0
    GGML_ASSERT(!(mode & GGML_SCALE_FLAG_ANTIALIAS) || (mode & 0xFF) == GGML_SCALE_MODE_BILINEAR);
5068
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
5069
5070
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type, ne0, ne1, ne2, ne3);
5071
5072
0
    ggml_set_op_params_i32(result, 0, (int32_t)mode);
5073
5074
0
    result->op     = GGML_OP_UPSCALE;
5075
0
    result->src[0] = a;
5076
5077
0
    return result;
5078
0
}
5079
5080
struct ggml_tensor * ggml_upscale(
5081
        struct ggml_context * ctx,
5082
        struct ggml_tensor  * a,
5083
        int                   scale_factor,
5084
0
        enum ggml_scale_mode  mode) {
5085
0
    GGML_ASSERT(scale_factor > 1);
5086
0
    return ggml_interpolate_impl(ctx, a, a->ne[0] * scale_factor, a->ne[1] * scale_factor, a->ne[2], a->ne[3], mode);
5087
0
}
5088
5089
struct ggml_tensor * ggml_upscale_ext(
5090
        struct ggml_context * ctx,
5091
        struct ggml_tensor  * a,
5092
        int                   ne0,
5093
        int                   ne1,
5094
        int                   ne2,
5095
        int                   ne3,
5096
0
        enum ggml_scale_mode  mode) {
5097
0
    return ggml_interpolate_impl(ctx, a, ne0, ne1, ne2, ne3, mode);
5098
0
}
5099
5100
struct ggml_tensor * ggml_interpolate(
5101
        struct ggml_context * ctx,
5102
        struct ggml_tensor  * a,
5103
        int64_t               ne0,
5104
        int64_t               ne1,
5105
        int64_t               ne2,
5106
        int64_t               ne3,
5107
0
        uint32_t              mode) {
5108
0
    return ggml_interpolate_impl(ctx, a, ne0, ne1, ne2, ne3, mode);
5109
0
}
5110
5111
// ggml_pad
5112
5113
struct ggml_tensor * ggml_pad(
5114
        struct ggml_context * ctx,
5115
        struct ggml_tensor  * a,
5116
        int                   p0,
5117
        int                   p1,
5118
        int                   p2,
5119
0
        int                   p3) {
5120
0
    return ggml_pad_ext(ctx, a, 0, p0, 0, p1, 0, p2, 0, p3);
5121
0
}
5122
5123
// ggml_pad_circular
5124
5125
struct ggml_tensor * ggml_pad_circular(
5126
        struct ggml_context * ctx,
5127
        struct ggml_tensor  * a,
5128
        int                   p0,
5129
        int                   p1,
5130
        int                   p2,
5131
0
        int                   p3) {
5132
0
    return ggml_pad_ext_circular(ctx, a, 0, p0, 0, p1, 0, p2, 0, p3);
5133
0
}
5134
5135
struct ggml_tensor * ggml_pad_ext(
5136
            struct ggml_context * ctx,
5137
            struct ggml_tensor  * a,
5138
            int                  lp0,
5139
            int                  rp0,
5140
            int                  lp1,
5141
            int                  rp1,
5142
            int                  lp2,
5143
            int                  rp2,
5144
            int                  lp3,
5145
            int                  rp3
5146
0
            ) {
5147
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
5148
0
            a->ne[0] + lp0 + rp0,
5149
0
            a->ne[1] + lp1 + rp1,
5150
0
            a->ne[2] + lp2 + rp2,
5151
0
            a->ne[3] + lp3 + rp3);
5152
5153
0
    ggml_set_op_params_i32(result, 0, lp0);
5154
0
    ggml_set_op_params_i32(result, 1, rp0);
5155
0
    ggml_set_op_params_i32(result, 2, lp1);
5156
0
    ggml_set_op_params_i32(result, 3, rp1);
5157
0
    ggml_set_op_params_i32(result, 4, lp2);
5158
0
    ggml_set_op_params_i32(result, 5, rp2);
5159
0
    ggml_set_op_params_i32(result, 6, lp3);
5160
0
    ggml_set_op_params_i32(result, 7, rp3);
5161
0
    ggml_set_op_params_i32(result, 8, 0); // not circular by default
5162
5163
5164
0
    result->op     = GGML_OP_PAD;
5165
0
    result->src[0] = a;
5166
5167
0
    return result;
5168
0
}
5169
5170
// ggml_pad_ext_circular
5171
5172
struct ggml_tensor * ggml_pad_ext_circular(
5173
        struct ggml_context * ctx,
5174
        struct ggml_tensor  * a,
5175
        int                  lp0,
5176
        int                  rp0,
5177
        int                  lp1,
5178
        int                  rp1,
5179
        int                  lp2,
5180
        int                  rp2,
5181
        int                  lp3,
5182
        int                  rp3
5183
0
        ) {
5184
0
    struct ggml_tensor * result = ggml_pad_ext(ctx, a, lp0, rp0, lp1, rp1, lp2, rp2, lp3, rp3);
5185
0
    ggml_set_op_params_i32(result, 8, 1); // circular
5186
0
    return result;
5187
0
}
5188
5189
// ggml_pad_reflect_1d
5190
5191
struct ggml_tensor * ggml_pad_reflect_1d(
5192
        struct ggml_context * ctx,
5193
        struct ggml_tensor  * a,
5194
        int                   p0,
5195
0
        int                   p1) {
5196
0
    GGML_ASSERT(p0 >= 0);
5197
0
    GGML_ASSERT(p1 >= 0);
5198
5199
0
    GGML_ASSERT(p0 < a->ne[0]); // padding length on each size must be less than the
5200
0
    GGML_ASSERT(p1 < a->ne[0]); // existing length of the dimension being padded
5201
5202
0
    GGML_ASSERT(ggml_is_contiguous(a));
5203
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
5204
5205
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, a->type,
5206
0
            a->ne[0] + p0 + p1,
5207
0
            a->ne[1],
5208
0
            a->ne[2],
5209
0
            a->ne[3]);
5210
5211
0
    int32_t params[] = { p0, p1 };
5212
0
    ggml_set_op_params(result, params, sizeof(params));
5213
5214
0
    result->op     = GGML_OP_PAD_REFLECT_1D;
5215
0
    result->src[0] = a;
5216
5217
0
    return result;
5218
0
}
5219
5220
// ggml_roll
5221
5222
struct ggml_tensor * ggml_roll(
5223
        struct ggml_context * ctx,
5224
        struct ggml_tensor  * a,
5225
        int                   shift0,
5226
        int                   shift1,
5227
        int                   shift2,
5228
0
        int                   shift3) {
5229
0
    GGML_ASSERT(a->nb[0] == ggml_type_size(a->type));
5230
0
    GGML_ASSERT(abs(shift0) < a->ne[0]);
5231
0
    GGML_ASSERT(abs(shift1) < a->ne[1]);
5232
0
    GGML_ASSERT(abs(shift2) < a->ne[2]);
5233
0
    GGML_ASSERT(abs(shift3) < a->ne[3]);
5234
5235
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
5236
5237
0
    ggml_set_op_params_i32(result, 0, shift0);
5238
0
    ggml_set_op_params_i32(result, 1, shift1);
5239
0
    ggml_set_op_params_i32(result, 2, shift2);
5240
0
    ggml_set_op_params_i32(result, 3, shift3);
5241
5242
0
    result->op     = GGML_OP_ROLL;
5243
0
    result->src[0] = a;
5244
5245
0
    return result;
5246
0
}
5247
5248
// ggml_timestep_embedding
5249
5250
struct ggml_tensor * ggml_timestep_embedding(
5251
        struct ggml_context * ctx,
5252
        struct ggml_tensor  * timesteps,
5253
        int                   dim,
5254
0
        int                   max_period) {
5255
5256
0
    struct ggml_tensor * result = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, dim, timesteps->ne[0]);
5257
5258
0
    ggml_set_op_params_i32(result, 0, dim);
5259
0
    ggml_set_op_params_i32(result, 1, max_period);
5260
5261
0
    result->op     = GGML_OP_TIMESTEP_EMBEDDING;
5262
0
    result->src[0] = timesteps;
5263
5264
0
    return result;
5265
0
}
5266
5267
// ggml_tri
5268
5269
struct ggml_tensor * ggml_tri(
5270
    struct ggml_context * ctx,
5271
    struct ggml_tensor  * a,
5272
0
    enum ggml_tri_type    type) {
5273
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
5274
5275
0
    GGML_ASSERT(ggml_is_contiguous(a));
5276
0
    GGML_ASSERT(a->ne[0] == a->ne[1]);
5277
5278
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, a);
5279
5280
0
    ggml_set_op_params_i32(result, 0, type);
5281
5282
0
    result->op = GGML_OP_TRI;
5283
0
    result->src[0] = a;
5284
5285
0
    return result;
5286
0
}
5287
5288
// ggml_fill
5289
5290
static struct ggml_tensor * ggml_fill_impl(
5291
    struct ggml_context * ctx,
5292
    struct ggml_tensor  * a,
5293
    float                 c,
5294
0
    bool                  inplace) {
5295
0
    GGML_ASSERT(a->type == GGML_TYPE_F32 || a->type == GGML_TYPE_F16);
5296
0
    GGML_ASSERT(ggml_is_contiguous(a));
5297
5298
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
5299
5300
0
    ggml_set_op_params_f32(result, 0, c);
5301
5302
0
    result->op = GGML_OP_FILL;
5303
0
    result->src[0] = a;
5304
5305
0
    return result;
5306
0
}
5307
5308
struct ggml_tensor * ggml_fill(
5309
    struct ggml_context * ctx,
5310
    struct ggml_tensor  * a,
5311
0
    float                 c) {
5312
0
    return ggml_fill_impl(ctx, a, c, false);
5313
0
}
5314
5315
struct ggml_tensor * ggml_fill_inplace(
5316
    struct ggml_context * ctx,
5317
    struct ggml_tensor  * a,
5318
0
    float                 c) {
5319
0
    return ggml_fill_impl(ctx, a, c, true);
5320
0
}
5321
5322
// ggml_argsort
5323
5324
struct ggml_tensor * ggml_argsort(
5325
        struct ggml_context  * ctx,
5326
        struct ggml_tensor   * a,
5327
0
        enum ggml_sort_order   order) {
5328
0
    GGML_ASSERT(a->ne[0] <= INT32_MAX);
5329
5330
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_I32, GGML_MAX_DIMS, a->ne);
5331
5332
0
    ggml_set_op_params_i32(result, 0, (int32_t) order);
5333
5334
0
    result->op     = GGML_OP_ARGSORT;
5335
0
    result->src[0] = a;
5336
5337
0
    return result;
5338
0
}
5339
5340
// ggml_argsort_top_k
5341
5342
struct ggml_tensor * ggml_argsort_top_k(
5343
        struct ggml_context * ctx,
5344
        struct ggml_tensor  * a,
5345
0
        int                   k) {
5346
0
    GGML_ASSERT(a->ne[0] >= k);
5347
5348
0
    struct ggml_tensor * result = ggml_argsort(ctx, a, GGML_SORT_ORDER_DESC);
5349
5350
0
    result = ggml_view_4d(ctx, result,
5351
0
                k, result->ne[1], result->ne[2], result->ne[3],
5352
0
                   result->nb[1], result->nb[2], result->nb[3],
5353
0
                0);
5354
5355
0
    return result;
5356
0
}
5357
5358
// ggml_top_k
5359
5360
struct ggml_tensor * ggml_top_k(
5361
        struct ggml_context * ctx,
5362
        struct ggml_tensor  * a,
5363
0
        int                   k) {
5364
0
    GGML_ASSERT(a->ne[0] >= k);
5365
5366
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, GGML_TYPE_I32, k, a->ne[1], a->ne[2], a->ne[3]);
5367
5368
0
    result->op     = GGML_OP_TOP_K;
5369
0
    result->src[0] = a;
5370
5371
0
    return result;
5372
0
}
5373
5374
// ggml_arange
5375
5376
struct ggml_tensor * ggml_arange(
5377
        struct ggml_context * ctx,
5378
        float                 start,
5379
        float                 stop,
5380
0
        float                 step) {
5381
0
    GGML_ASSERT(stop > start);
5382
5383
0
    const int64_t steps = (int64_t) ceilf((stop - start) / step);
5384
5385
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, steps);
5386
5387
0
    ggml_set_op_params_f32(result, 0, start);
5388
0
    ggml_set_op_params_f32(result, 1, stop);
5389
0
    ggml_set_op_params_f32(result, 2, step);
5390
5391
0
    result->op = GGML_OP_ARANGE;
5392
5393
0
    return result;
5394
0
}
5395
5396
// ggml_flash_attn_ext
5397
5398
struct ggml_tensor * ggml_flash_attn_ext(
5399
        struct ggml_context * ctx,
5400
        struct ggml_tensor  * q,
5401
        struct ggml_tensor  * k,
5402
        struct ggml_tensor  * v,
5403
        struct ggml_tensor  * mask,
5404
        float                 scale,
5405
        float                 max_bias,
5406
0
        float                 logit_softcap) {
5407
0
    GGML_ASSERT(ggml_can_mul_mat(k, q));
5408
    // TODO: check if vT can be multiplied by (k*qT)
5409
5410
0
    GGML_ASSERT(q->ne[3] == k->ne[3]);
5411
0
    GGML_ASSERT(q->ne[3] == v->ne[3]);
5412
5413
0
    if (mask) {
5414
0
        GGML_ASSERT(mask->type == GGML_TYPE_F16);
5415
0
        GGML_ASSERT(ggml_is_contiguous(mask));
5416
        //GGML_ASSERT(ggml_can_repeat_rows(mask, qk));
5417
5418
0
        GGML_ASSERT(q->ne[2] % mask->ne[2] == 0);
5419
0
        GGML_ASSERT(q->ne[3] % mask->ne[3] == 0);
5420
0
    }
5421
5422
0
    if (max_bias > 0.0f) {
5423
0
        GGML_ASSERT(mask);
5424
0
    }
5425
5426
    // permute(0, 2, 1, 3)
5427
0
    int64_t ne[4] = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] };
5428
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5429
5430
0
    float params[] = { scale, max_bias, logit_softcap };
5431
0
    ggml_set_op_params(result, params, sizeof(params));
5432
5433
0
    result->op     = GGML_OP_FLASH_ATTN_EXT;
5434
0
    result->src[0] = q;
5435
0
    result->src[1] = k;
5436
0
    result->src[2] = v;
5437
0
    result->src[3] = mask;
5438
5439
0
    return result;
5440
0
}
5441
5442
void ggml_flash_attn_ext_set_prec(
5443
        struct ggml_tensor * a,
5444
0
        enum ggml_prec       prec) {
5445
0
    GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
5446
5447
0
    const int32_t prec_i32 = (int32_t) prec;
5448
5449
0
    ggml_set_op_params_i32(a, 3, prec_i32); // scale is on first pos, max_bias on second
5450
0
}
5451
5452
enum ggml_prec ggml_flash_attn_ext_get_prec(
5453
0
        const struct ggml_tensor * a) {
5454
0
    GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
5455
5456
0
    const int32_t prec_i32 = ggml_get_op_params_i32(a, 3);
5457
5458
0
    return (enum ggml_prec) prec_i32;
5459
0
}
5460
5461
void ggml_flash_attn_ext_add_sinks(
5462
        struct ggml_tensor * a,
5463
0
        struct ggml_tensor * sinks) {
5464
0
    if (!sinks) {
5465
0
        a->src[4] = NULL;
5466
0
        return;
5467
0
    }
5468
5469
0
    GGML_ASSERT(a->op == GGML_OP_FLASH_ATTN_EXT);
5470
0
    GGML_ASSERT(a->src[4] == NULL);
5471
0
    GGML_ASSERT(a->src[0]->ne[2] == sinks->ne[0]);
5472
0
    GGML_ASSERT(sinks->type == GGML_TYPE_F32);
5473
5474
0
    a->src[4] = sinks;
5475
0
}
5476
5477
// ggml_flash_attn_back
5478
5479
struct ggml_tensor * ggml_flash_attn_back(
5480
        struct ggml_context * ctx,
5481
        struct ggml_tensor  * q,
5482
        struct ggml_tensor  * k,
5483
        struct ggml_tensor  * v,
5484
        struct ggml_tensor  * d,
5485
0
        bool                  masked) {
5486
0
    GGML_ABORT("TODO: adapt to ggml_flash_attn_ext() changes");
5487
5488
0
    GGML_ASSERT(ggml_can_mul_mat(k, q));
5489
    // TODO: check if vT can be multiplied by (k*qT)
5490
5491
    // d shape [D,N,ne2,ne3]
5492
    // q shape [D,N,ne2,ne3]
5493
    // k shape [D,M,kvne2,ne3]
5494
    // v shape [M,D,kvne2,ne3]
5495
5496
0
    const int64_t     D = q->ne[0];
5497
0
    const int64_t     N = q->ne[1];
5498
0
    const int64_t     M = k->ne[1];
5499
0
    const int64_t   ne2 = q->ne[2];
5500
0
    const int64_t   ne3 = q->ne[3];
5501
0
    const int64_t kvne2 = k->ne[2];
5502
5503
0
    GGML_ASSERT(k->ne[0] == D);
5504
0
    GGML_ASSERT(v->ne[0] == M);
5505
0
    GGML_ASSERT(v->ne[1] == D);
5506
0
    GGML_ASSERT(d->ne[0] == D);
5507
0
    GGML_ASSERT(d->ne[1] == N);
5508
0
    GGML_ASSERT(k->ne[2] == kvne2);
5509
0
    GGML_ASSERT(k->ne[3] == ne3);
5510
0
    GGML_ASSERT(v->ne[2] == kvne2);
5511
0
    GGML_ASSERT(v->ne[3] == ne3);
5512
0
    GGML_ASSERT(d->ne[2] == ne2);
5513
0
    GGML_ASSERT(d->ne[3] == ne3);
5514
5515
0
    GGML_ASSERT(ne2 % kvne2 == 0);
5516
5517
    // store gradients of q, k and v as continuous tensors concatenated in result.
5518
    // note: v and gradv are actually transposed, i.e. v->ne[0] != D.
5519
0
    const int64_t elem_q = ggml_nelements(q);
5520
0
    const int64_t elem_k = ggml_nelements(k);
5521
0
    const int64_t elem_v = ggml_nelements(v);
5522
5523
0
    enum ggml_type result_type = GGML_TYPE_F32;
5524
0
    GGML_ASSERT(ggml_blck_size(result_type) == 1);
5525
0
    const size_t tsize = ggml_type_size(result_type);
5526
5527
0
    const size_t offs_q = 0;
5528
0
    const size_t offs_k = offs_q + GGML_PAD(elem_q * tsize, GGML_MEM_ALIGN);
5529
0
    const size_t offs_v = offs_k + GGML_PAD(elem_k * tsize, GGML_MEM_ALIGN);
5530
0
    const size_t end    = offs_v + GGML_PAD(elem_v * tsize, GGML_MEM_ALIGN);
5531
5532
0
    const size_t nelements = (end + tsize - 1)/tsize;
5533
5534
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, nelements);
5535
5536
0
    int32_t masked_i = masked ? 1 : 0;
5537
0
    ggml_set_op_params(result, &masked_i, sizeof(masked_i));
5538
5539
0
    result->op     = GGML_OP_FLASH_ATTN_BACK;
5540
0
    result->src[0] = q;
5541
0
    result->src[1] = k;
5542
0
    result->src[2] = v;
5543
0
    result->src[3] = d;
5544
5545
0
    return result;
5546
0
}
5547
5548
// ggml_ssm_conv
5549
5550
struct ggml_tensor * ggml_ssm_conv(
5551
        struct ggml_context * ctx,
5552
        struct ggml_tensor  * sx,
5553
0
        struct ggml_tensor  * c) {
5554
0
    GGML_ASSERT(ggml_is_3d(sx));
5555
0
    GGML_ASSERT(ggml_is_matrix(c));
5556
5557
0
    const int64_t d_conv  = c->ne[0];
5558
0
    const int64_t d_inner = c->ne[1];
5559
0
    const int64_t n_t     = sx->ne[0] - d_conv + 1; // tokens per sequence
5560
0
    const int64_t n_s     = sx->ne[2];
5561
5562
    // TODO: maybe support other strides than 1?
5563
0
    GGML_ASSERT(sx->ne[0] == d_conv - 1 + n_t);
5564
0
    GGML_ASSERT(sx->ne[1] == d_inner);
5565
0
    GGML_ASSERT(n_t >= 0);
5566
5567
0
    struct ggml_tensor * result = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, d_inner, n_t, n_s);
5568
5569
0
    result->op     = GGML_OP_SSM_CONV;
5570
0
    result->src[0] = sx;
5571
0
    result->src[1] = c;
5572
5573
0
    return result;
5574
0
}
5575
5576
// ggml_ssm_scan
5577
5578
struct ggml_tensor * ggml_ssm_scan(
5579
        struct ggml_context * ctx,
5580
        struct ggml_tensor  * s,
5581
        struct ggml_tensor  * x,
5582
        struct ggml_tensor  * dt,
5583
        struct ggml_tensor  * A,
5584
        struct ggml_tensor  * B,
5585
        struct ggml_tensor  * C,
5586
0
        struct ggml_tensor  * ids) {
5587
0
    GGML_ASSERT(ggml_is_contiguous(s));
5588
0
    GGML_ASSERT(ggml_is_contiguous(dt));
5589
0
    GGML_ASSERT(ggml_is_contiguous(A));
5590
0
    GGML_ASSERT(x->nb[0] == ggml_type_size(x->type));
5591
0
    GGML_ASSERT(B->nb[0] == ggml_type_size(B->type));
5592
0
    GGML_ASSERT(C->nb[0] == ggml_type_size(C->type));
5593
0
    GGML_ASSERT(x->nb[1] == x->ne[0]*x->nb[0]);
5594
0
    GGML_ASSERT(B->nb[1] == B->ne[0]*B->nb[0]);
5595
0
    GGML_ASSERT(C->nb[1] == C->ne[0]*C->nb[0]);
5596
0
    GGML_ASSERT(ggml_are_same_shape(B, C));
5597
0
    GGML_ASSERT(ids->type == GGML_TYPE_I32);
5598
5599
0
    {
5600
0
        const int64_t d_state      = s->ne[0];
5601
0
        const int64_t head_dim     = x->ne[0];
5602
0
        const int64_t n_head       = x->ne[1];
5603
0
        const int64_t n_seq_tokens = x->ne[2];
5604
0
        const int64_t n_seqs       = x->ne[3];
5605
5606
0
        GGML_ASSERT(dt->ne[0] == n_head);
5607
0
        GGML_ASSERT(dt->ne[1] == n_seq_tokens);
5608
0
        GGML_ASSERT(dt->ne[2] == n_seqs);
5609
0
        GGML_ASSERT(ggml_is_3d(dt));
5610
0
        GGML_ASSERT(s->ne[1] == head_dim);
5611
0
        GGML_ASSERT(s->ne[2] == n_head);
5612
0
        GGML_ASSERT(B->ne[0] == d_state);
5613
0
        GGML_ASSERT(B->ne[2] == n_seq_tokens);
5614
0
        GGML_ASSERT(B->ne[3] == n_seqs);
5615
0
        GGML_ASSERT(ids->ne[0] == n_seqs);
5616
0
        GGML_ASSERT(ggml_is_vector(ids));
5617
0
        GGML_ASSERT(A->ne[1] == n_head);
5618
0
        GGML_ASSERT(ggml_is_matrix(A));
5619
5620
0
        if (A->ne[0] != 1) {
5621
            // Mamba-1 has more granular decay factors
5622
0
            GGML_ASSERT(A->ne[0] == d_state);
5623
0
        }
5624
0
    }
5625
5626
    // concatenated y + ssm_states
5627
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, ggml_nelements(x) + s->ne[0]*s->ne[1]*s->ne[2]*ids->ne[0]);
5628
5629
0
    result->op   = GGML_OP_SSM_SCAN;
5630
0
    result->src[0] = s;
5631
0
    result->src[1] = x;
5632
0
    result->src[2] = dt;
5633
0
    result->src[3] = A;
5634
0
    result->src[4] = B;
5635
0
    result->src[5] = C;
5636
0
    result->src[6] = ids;
5637
5638
0
    return result;
5639
0
}
5640
5641
// ggml_win_part
5642
5643
struct ggml_tensor * ggml_win_part(
5644
        struct ggml_context * ctx,
5645
        struct ggml_tensor  * a,
5646
0
        int                   w) {
5647
0
    GGML_ASSERT(a->ne[3] == 1);
5648
0
    GGML_ASSERT(a->type  == GGML_TYPE_F32);
5649
5650
    // padding
5651
0
    const int px = (w - a->ne[1]%w)%w;
5652
0
    const int py = (w - a->ne[2]%w)%w;
5653
5654
0
    const int npx = (px + a->ne[1])/w;
5655
0
    const int npy = (py + a->ne[2])/w;
5656
0
    const int np  = npx*npy;
5657
5658
0
    const int64_t ne[4] = { a->ne[0], w, w, np, };
5659
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5660
5661
0
    int32_t params[] = { npx, npy, w };
5662
0
    ggml_set_op_params(result, params, sizeof(params));
5663
5664
0
    result->op     = GGML_OP_WIN_PART;
5665
0
    result->src[0] = a;
5666
5667
0
    return result;
5668
0
}
5669
5670
// ggml_win_unpart
5671
5672
struct ggml_tensor * ggml_win_unpart(
5673
        struct ggml_context * ctx,
5674
        struct ggml_tensor  * a,
5675
        int                   w0,
5676
        int                   h0,
5677
0
        int                   w) {
5678
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
5679
5680
0
    const int64_t ne[4] = { a->ne[0], w0, h0, 1, };
5681
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 3, ne);
5682
5683
0
    int32_t params[] = { w };
5684
0
    ggml_set_op_params(result, params, sizeof(params));
5685
5686
0
    result->op     = GGML_OP_WIN_UNPART;
5687
0
    result->src[0] = a;
5688
5689
0
    return result;
5690
0
}
5691
5692
// ggml_get_rel_pos
5693
5694
struct ggml_tensor * ggml_get_rel_pos(
5695
        struct ggml_context * ctx,
5696
        struct ggml_tensor  * a,
5697
        int                   qh,
5698
0
        int                   kh) {
5699
0
    GGML_ASSERT(qh == kh);
5700
0
    GGML_ASSERT(2*MAX(qh, kh) - 1 == a->ne[1]);
5701
5702
0
    const int64_t ne[4] = { a->ne[0], kh, qh, 1, };
5703
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F16, 3, ne);
5704
5705
0
    result->op     = GGML_OP_GET_REL_POS;
5706
0
    result->src[0] = a;
5707
5708
0
    return result;
5709
0
}
5710
5711
// ggml_add_rel_pos
5712
5713
static struct ggml_tensor * ggml_add_rel_pos_impl(
5714
        struct ggml_context * ctx,
5715
        struct ggml_tensor  * a,
5716
        struct ggml_tensor  * pw,
5717
        struct ggml_tensor  * ph,
5718
0
        bool                  inplace) {
5719
0
    GGML_ASSERT(ggml_are_same_shape(pw, ph));
5720
0
    GGML_ASSERT(ggml_is_contiguous(a));
5721
0
    GGML_ASSERT(ggml_is_contiguous(pw));
5722
0
    GGML_ASSERT(ggml_is_contiguous(ph));
5723
0
    GGML_ASSERT(ph->type == GGML_TYPE_F32);
5724
0
    GGML_ASSERT(pw->type == GGML_TYPE_F32);
5725
0
    GGML_ASSERT(pw->ne[3] == a->ne[2]);
5726
0
    GGML_ASSERT(pw->ne[0]*pw->ne[0] == a->ne[0]);
5727
0
    GGML_ASSERT(pw->ne[1]*pw->ne[2] == a->ne[1]);
5728
5729
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
5730
0
    ggml_set_op_params_i32(result, 0, inplace ? 1 : 0);
5731
5732
0
    result->op     = GGML_OP_ADD_REL_POS;
5733
0
    result->src[0] = a;
5734
0
    result->src[1] = pw;
5735
0
    result->src[2] = ph;
5736
5737
0
    return result;
5738
0
}
5739
5740
struct ggml_tensor * ggml_add_rel_pos(
5741
        struct ggml_context * ctx,
5742
        struct ggml_tensor  * a,
5743
        struct ggml_tensor  * pw,
5744
0
        struct ggml_tensor  * ph) {
5745
0
    return ggml_add_rel_pos_impl(ctx, a, pw, ph, false);
5746
0
}
5747
5748
struct ggml_tensor * ggml_add_rel_pos_inplace(
5749
        struct ggml_context * ctx,
5750
        struct ggml_tensor  * a,
5751
        struct ggml_tensor  * pw,
5752
0
        struct ggml_tensor  * ph) {
5753
0
    return ggml_add_rel_pos_impl(ctx, a, pw, ph, true);
5754
0
}
5755
5756
// ggml_rwkv_wkv6
5757
5758
struct ggml_tensor * ggml_rwkv_wkv6(
5759
        struct ggml_context * ctx,
5760
        struct ggml_tensor  * k,
5761
        struct ggml_tensor  * v,
5762
        struct ggml_tensor  * r,
5763
        struct ggml_tensor  * tf,
5764
        struct ggml_tensor  * td,
5765
0
        struct ggml_tensor  * state) {
5766
0
    GGML_ASSERT(ggml_is_contiguous(k));
5767
0
    GGML_ASSERT(ggml_is_contiguous(v));
5768
0
    GGML_ASSERT(ggml_is_contiguous(r));
5769
0
    GGML_ASSERT(ggml_is_contiguous(tf));
5770
0
    GGML_ASSERT(ggml_is_contiguous(td));
5771
0
    GGML_ASSERT(ggml_is_contiguous(state));
5772
5773
0
    const int64_t S = k->ne[0];
5774
0
    const int64_t H = k->ne[1];
5775
0
    const int64_t n_tokens = k->ne[2];
5776
0
    const int64_t n_seqs = state->ne[1];
5777
0
    {
5778
0
        GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
5779
0
        GGML_ASSERT(r->ne[0] == S && r->ne[1] == H && r->ne[2] == n_tokens);
5780
0
        GGML_ASSERT(td->ne[0] == S && td->ne[1] == H && td->ne[2] == n_tokens);
5781
0
        GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
5782
0
    }
5783
5784
    // concat output and new_state
5785
0
    const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
5786
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5787
5788
0
    result->op     = GGML_OP_RWKV_WKV6;
5789
0
    result->src[0] = k;
5790
0
    result->src[1] = v;
5791
0
    result->src[2] = r;
5792
0
    result->src[3] = tf;
5793
0
    result->src[4] = td;
5794
0
    result->src[5] = state;
5795
5796
0
    return result;
5797
0
}
5798
5799
// ggml_gated_linear_attn
5800
5801
struct ggml_tensor * ggml_gated_linear_attn(
5802
        struct ggml_context * ctx,
5803
        struct ggml_tensor  * k,
5804
        struct ggml_tensor  * v,
5805
        struct ggml_tensor  * q,
5806
        struct ggml_tensor  * g,
5807
        struct ggml_tensor  * state,
5808
0
        float scale) {
5809
0
    GGML_ASSERT(ggml_is_contiguous(k));
5810
0
    GGML_ASSERT(ggml_is_contiguous(v));
5811
0
    GGML_ASSERT(ggml_is_contiguous(q));
5812
0
    GGML_ASSERT(ggml_is_contiguous(g));
5813
0
    GGML_ASSERT(ggml_is_contiguous(state));
5814
5815
0
    const int64_t S = k->ne[0];
5816
0
    const int64_t H = k->ne[1];
5817
0
    const int64_t n_tokens = k->ne[2];
5818
0
    const int64_t n_seqs = state->ne[1];
5819
0
    {
5820
0
        GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
5821
0
        GGML_ASSERT(q->ne[0] == S && q->ne[1] == H && q->ne[2] == n_tokens);
5822
0
        GGML_ASSERT(g->ne[0] == S && g->ne[1] == H && g->ne[2] == n_tokens);
5823
0
        GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
5824
0
    }
5825
5826
    // concat output and new_state
5827
0
    const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
5828
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5829
5830
0
    ggml_set_op_params_f32(result, 0, scale);
5831
5832
0
    result->op     = GGML_OP_GATED_LINEAR_ATTN;
5833
0
    result->src[0] = k;
5834
0
    result->src[1] = v;
5835
0
    result->src[2] = q;
5836
0
    result->src[3] = g;
5837
0
    result->src[4] = state;
5838
5839
0
    return result;
5840
0
}
5841
5842
// ggml_rwkv_wkv7
5843
5844
struct ggml_tensor * ggml_rwkv_wkv7(
5845
        struct ggml_context * ctx,
5846
        struct ggml_tensor  * r,
5847
        struct ggml_tensor  * w,
5848
        struct ggml_tensor  * k,
5849
        struct ggml_tensor  * v,
5850
        struct ggml_tensor  * a,
5851
        struct ggml_tensor  * b,
5852
0
        struct ggml_tensor  * state) {
5853
0
    GGML_ASSERT(ggml_is_contiguous(r));
5854
0
    GGML_ASSERT(ggml_is_contiguous(w));
5855
0
    GGML_ASSERT(ggml_is_contiguous(k));
5856
0
    GGML_ASSERT(ggml_is_contiguous(v));
5857
0
    GGML_ASSERT(ggml_is_contiguous(a));
5858
0
    GGML_ASSERT(ggml_is_contiguous(b));
5859
0
    GGML_ASSERT(ggml_is_contiguous(state));
5860
5861
0
    const int64_t S = k->ne[0];
5862
0
    const int64_t H = k->ne[1];
5863
0
    const int64_t n_tokens = k->ne[2];
5864
0
    const int64_t n_seqs = state->ne[1];
5865
0
    {
5866
0
        GGML_ASSERT(w->ne[0] == S && w->ne[1] == H && w->ne[2] == n_tokens);
5867
0
        GGML_ASSERT(k->ne[0] == S && k->ne[1] == H && k->ne[2] == n_tokens);
5868
0
        GGML_ASSERT(v->ne[0] == S && v->ne[1] == H && v->ne[2] == n_tokens);
5869
0
        GGML_ASSERT(a->ne[0] == S && a->ne[1] == H && a->ne[2] == n_tokens);
5870
0
        GGML_ASSERT(b->ne[0] == S && b->ne[1] == H && b->ne[2] == n_tokens);
5871
0
        GGML_ASSERT(ggml_nelements(state) == S * S * H * n_seqs);
5872
0
    }
5873
5874
    // concat output and new_state
5875
0
    const int64_t ne[4] = { S * H, n_tokens + S * n_seqs, 1, 1 };
5876
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
5877
5878
0
    result->op     = GGML_OP_RWKV_WKV7;
5879
0
    result->src[0] = r;
5880
0
    result->src[1] = w;
5881
0
    result->src[2] = k;
5882
0
    result->src[3] = v;
5883
0
    result->src[4] = a;
5884
0
    result->src[5] = b;
5885
0
    result->src[6] = state;
5886
5887
0
    return result;
5888
0
}
5889
5890
// ggml_unary
5891
5892
static struct ggml_tensor * ggml_unary_impl(
5893
        struct ggml_context * ctx,
5894
        struct ggml_tensor  * a,
5895
        enum ggml_unary_op    op,
5896
0
        bool                  inplace) {
5897
0
    GGML_ASSERT(ggml_is_contiguous_rows(a));
5898
5899
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
5900
5901
0
    ggml_set_op_params_i32(result, 0, (int32_t) op);
5902
5903
0
    result->op     = GGML_OP_UNARY;
5904
0
    result->src[0] = a;
5905
5906
0
    return result;
5907
0
}
5908
5909
struct ggml_tensor * ggml_unary(
5910
        struct ggml_context * ctx,
5911
        struct ggml_tensor  * a,
5912
0
        enum ggml_unary_op    op) {
5913
0
    return ggml_unary_impl(ctx, a, op, false);
5914
0
}
5915
5916
struct ggml_tensor * ggml_unary_inplace(
5917
        struct ggml_context * ctx,
5918
        struct ggml_tensor  * a,
5919
0
        enum ggml_unary_op    op) {
5920
0
    return ggml_unary_impl(ctx, a, op, true);
5921
0
}
5922
5923
// ggml_map_custom1
5924
5925
static struct ggml_tensor * ggml_map_custom1_impl(
5926
        struct ggml_context      * ctx,
5927
        struct ggml_tensor       * a,
5928
        const  ggml_custom1_op_t   fun,
5929
        int                        n_tasks,
5930
        void                     * userdata,
5931
0
        bool                       inplace) {
5932
0
    GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
5933
5934
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
5935
5936
0
    struct ggml_map_custom1_op_params params = {
5937
0
        /*.fun      =*/ fun,
5938
0
        /*.n_tasks  =*/ n_tasks,
5939
0
        /*.userdata =*/ userdata
5940
0
    };
5941
0
    ggml_set_op_params(result, &params, sizeof(params));
5942
5943
0
    result->op     = GGML_OP_MAP_CUSTOM1;
5944
0
    result->src[0] = a;
5945
5946
0
    return result;
5947
0
}
5948
5949
struct ggml_tensor * ggml_map_custom1(
5950
        struct ggml_context      * ctx,
5951
        struct ggml_tensor       * a,
5952
        const  ggml_custom1_op_t   fun,
5953
        int                        n_tasks,
5954
0
        void                     * userdata) {
5955
0
    return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, false);
5956
0
}
5957
5958
struct ggml_tensor * ggml_map_custom1_inplace(
5959
        struct ggml_context      * ctx,
5960
        struct ggml_tensor       * a,
5961
        const  ggml_custom1_op_t   fun,
5962
        int                        n_tasks,
5963
0
        void                     * userdata) {
5964
0
    return ggml_map_custom1_impl(ctx, a, fun, n_tasks, userdata, true);
5965
0
}
5966
5967
// ggml_map_custom2
5968
5969
static struct ggml_tensor * ggml_map_custom2_impl(
5970
        struct ggml_context      * ctx,
5971
        struct ggml_tensor       * a,
5972
        struct ggml_tensor       * b,
5973
        const  ggml_custom2_op_t   fun,
5974
        int                        n_tasks,
5975
        void                     * userdata,
5976
0
        bool                       inplace) {
5977
0
    GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
5978
5979
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
5980
5981
0
    struct ggml_map_custom2_op_params params = {
5982
0
        /*.fun      =*/ fun,
5983
0
        /*.n_tasks  =*/ n_tasks,
5984
0
        /*.userdata =*/ userdata
5985
0
    };
5986
0
    ggml_set_op_params(result, &params, sizeof(params));
5987
5988
0
    result->op     = GGML_OP_MAP_CUSTOM2;
5989
0
    result->src[0] = a;
5990
0
    result->src[1] = b;
5991
5992
0
    return result;
5993
0
}
5994
5995
struct ggml_tensor * ggml_map_custom2(
5996
        struct ggml_context      * ctx,
5997
        struct ggml_tensor       * a,
5998
        struct ggml_tensor       * b,
5999
        const  ggml_custom2_op_t   fun,
6000
        int                        n_tasks,
6001
0
        void                     * userdata) {
6002
0
    return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, false);
6003
0
}
6004
6005
struct ggml_tensor * ggml_map_custom2_inplace(
6006
        struct ggml_context      * ctx,
6007
        struct ggml_tensor       * a,
6008
        struct ggml_tensor       * b,
6009
        const  ggml_custom2_op_t   fun,
6010
        int                        n_tasks,
6011
0
        void                     * userdata) {
6012
0
    return ggml_map_custom2_impl(ctx, a, b, fun, n_tasks, userdata, true);
6013
0
}
6014
6015
// ggml_map_custom3
6016
6017
static struct ggml_tensor * ggml_map_custom3_impl(
6018
        struct ggml_context      * ctx,
6019
        struct ggml_tensor       * a,
6020
        struct ggml_tensor       * b,
6021
        struct ggml_tensor       * c,
6022
        const  ggml_custom3_op_t   fun,
6023
        int                        n_tasks,
6024
        void                     * userdata,
6025
0
        bool                       inplace) {
6026
0
    GGML_ASSERT(n_tasks == GGML_N_TASKS_MAX || n_tasks > 0);
6027
6028
0
    struct ggml_tensor * result = inplace ? ggml_view_tensor(ctx, a) : ggml_dup_tensor(ctx, a);
6029
6030
0
    struct ggml_map_custom3_op_params params = {
6031
0
        /*.fun      =*/ fun,
6032
0
        /*.n_tasks  =*/ n_tasks,
6033
0
        /*.userdata =*/ userdata
6034
0
    };
6035
0
    ggml_set_op_params(result, &params, sizeof(params));
6036
6037
0
    result->op     = GGML_OP_MAP_CUSTOM3;
6038
0
    result->src[0] = a;
6039
0
    result->src[1] = b;
6040
0
    result->src[2] = c;
6041
6042
0
    return result;
6043
0
}
6044
6045
struct ggml_tensor * ggml_map_custom3(
6046
        struct ggml_context      * ctx,
6047
        struct ggml_tensor       * a,
6048
        struct ggml_tensor       * b,
6049
        struct ggml_tensor       * c,
6050
        const  ggml_custom3_op_t   fun,
6051
        int                        n_tasks,
6052
0
        void                     * userdata) {
6053
0
    return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, false);
6054
0
}
6055
6056
struct ggml_tensor * ggml_map_custom3_inplace(
6057
        struct ggml_context      * ctx,
6058
        struct ggml_tensor       * a,
6059
        struct ggml_tensor       * b,
6060
        struct ggml_tensor       * c,
6061
        const  ggml_custom3_op_t   fun,
6062
        int                        n_tasks,
6063
0
        void                     * userdata) {
6064
0
    return ggml_map_custom3_impl(ctx, a, b, c, fun, n_tasks, userdata, true);
6065
0
}
6066
6067
struct ggml_tensor * ggml_custom_4d(
6068
        struct ggml_context * ctx,
6069
        enum ggml_type        type,
6070
        int64_t               ne0,
6071
        int64_t               ne1,
6072
        int64_t               ne2,
6073
        int64_t               ne3,
6074
        struct ggml_tensor ** args,
6075
        int                   n_args,
6076
        ggml_custom_op_t      fun,
6077
        int                   n_tasks,
6078
0
        void                * userdata) {
6079
6080
0
    GGML_ASSERT(n_args < GGML_MAX_SRC);
6081
6082
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, type, ne0, ne1, ne2, ne3);
6083
6084
0
    struct ggml_custom_op_params params = {
6085
0
        /*.fun      =*/ fun,
6086
0
        /*.n_tasks  =*/ n_tasks,
6087
0
        /*.userdata =*/ userdata
6088
0
    };
6089
0
    ggml_set_op_params(result, &params, sizeof(params));
6090
6091
0
    result->op = GGML_OP_CUSTOM;
6092
0
    for (int i = 0; i < n_args; i++) {
6093
0
        result->src[i] = args[i];
6094
0
    }
6095
6096
0
    return result;
6097
0
}
6098
6099
struct ggml_tensor * ggml_custom_inplace(
6100
        struct ggml_context * ctx,
6101
        struct ggml_tensor  * a,
6102
        struct ggml_tensor ** args,
6103
        int                   n_args,
6104
        ggml_custom_op_t      fun,
6105
        int                   n_tasks,
6106
0
        void                * userdata) {
6107
6108
0
    GGML_ASSERT(n_args < GGML_MAX_SRC - 1);
6109
6110
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
6111
6112
0
    struct ggml_custom_op_params params = {
6113
0
        /*.fun      =*/ fun,
6114
0
        /*.n_tasks  =*/ n_tasks,
6115
0
        /*.userdata =*/ userdata
6116
0
    };
6117
0
    ggml_set_op_params(result, &params, sizeof(params));
6118
6119
0
    result->op = GGML_OP_CUSTOM;
6120
0
    result->src[0] = a;
6121
0
    for (int i = 0; i < n_args; i++) {
6122
0
        result->src[i + 1] = args[i];
6123
0
    }
6124
6125
0
    return result;
6126
0
}
6127
// ggml_cross_entropy_loss
6128
6129
struct ggml_tensor * ggml_cross_entropy_loss(
6130
        struct ggml_context * ctx,
6131
        struct ggml_tensor  * a,
6132
0
        struct ggml_tensor  * b) {
6133
0
    GGML_ASSERT(ggml_are_same_shape(a, b));
6134
6135
0
    struct ggml_tensor * result = ggml_new_tensor_1d(ctx, a->type, 1);
6136
6137
0
    result->op     = GGML_OP_CROSS_ENTROPY_LOSS;
6138
0
    result->src[0] = a;
6139
0
    result->src[1] = b;
6140
6141
0
    return result;
6142
0
}
6143
6144
// ggml_cross_entropy_loss_back
6145
6146
struct ggml_tensor * ggml_cross_entropy_loss_back(
6147
        struct ggml_context * ctx,
6148
        struct ggml_tensor  * a,
6149
        struct ggml_tensor  * b,
6150
0
        struct ggml_tensor  * c) {
6151
0
    GGML_ASSERT(ggml_is_scalar(a));
6152
0
    GGML_ASSERT(ggml_are_same_shape(b, c));
6153
6154
0
    struct ggml_tensor * result = ggml_dup_tensor(ctx, b);
6155
6156
0
    result->op     = GGML_OP_CROSS_ENTROPY_LOSS_BACK;
6157
0
    result->src[0] = a;
6158
0
    result->src[1] = b;
6159
0
    result->src[2] = c;
6160
6161
0
    return result;
6162
0
}
6163
6164
// opt_step_adamw
6165
6166
struct ggml_tensor * ggml_opt_step_adamw(
6167
        struct ggml_context * ctx,
6168
        struct ggml_tensor  * a,
6169
        struct ggml_tensor  * grad,
6170
        struct ggml_tensor  * m,
6171
        struct ggml_tensor  * v,
6172
0
        struct ggml_tensor  * adamw_params) {
6173
0
    GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
6174
0
    GGML_ASSERT(ggml_are_same_shape(a, grad));
6175
0
    GGML_ASSERT(ggml_are_same_shape(a, m));
6176
0
    GGML_ASSERT(ggml_are_same_shape(a, v));
6177
0
    GGML_ASSERT(adamw_params->type == GGML_TYPE_F32);
6178
0
    GGML_ASSERT(ggml_nelements(adamw_params) == 7);
6179
6180
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
6181
6182
0
    result->op     = GGML_OP_OPT_STEP_ADAMW;
6183
0
    result->src[0] = a;
6184
0
    result->src[1] = grad;
6185
0
    result->src[2] = m;
6186
0
    result->src[3] = v;
6187
0
    result->src[4] = adamw_params;
6188
6189
0
    return result;
6190
0
}
6191
6192
// opt_step_sgd
6193
6194
struct ggml_tensor * ggml_opt_step_sgd(
6195
        struct ggml_context * ctx,
6196
        struct ggml_tensor  * a,
6197
        struct ggml_tensor  * grad,
6198
0
        struct ggml_tensor  * params) {
6199
0
    GGML_ASSERT(a->flags & GGML_TENSOR_FLAG_PARAM);
6200
0
    GGML_ASSERT(ggml_are_same_shape(a, grad));
6201
0
    GGML_ASSERT(params->type == GGML_TYPE_F32);
6202
0
    GGML_ASSERT(ggml_nelements(params) == 2);
6203
6204
0
    struct ggml_tensor * result = ggml_view_tensor(ctx, a);
6205
6206
0
    result->op     = GGML_OP_OPT_STEP_SGD;
6207
0
    result->src[0] = a;
6208
0
    result->src[1] = grad;
6209
0
    result->src[2] = params;
6210
6211
0
    return result;
6212
0
}
6213
6214
// solve_tri
6215
6216
struct ggml_tensor * ggml_solve_tri(
6217
        struct ggml_context * ctx,
6218
        struct ggml_tensor  * a,
6219
        struct ggml_tensor  * b,
6220
        bool                  left,
6221
        bool                  lower,
6222
0
        bool                  uni) {
6223
0
    GGML_ASSERT(a->type == GGML_TYPE_F32);
6224
0
    GGML_ASSERT(b->type == GGML_TYPE_F32);
6225
6226
    // A must be square and lower diagonal
6227
0
    GGML_ASSERT(a->ne[0] == a->ne[1]);
6228
    // B must have same outer dimension as A
6229
0
    GGML_ASSERT(a->ne[1] == b->ne[1]);
6230
6231
    // batch dimensions must be equal
6232
0
    GGML_ASSERT(a->ne[2] == b->ne[2]);
6233
0
    GGML_ASSERT(a->ne[3] == b->ne[3]);
6234
6235
0
    GGML_ASSERT(ggml_is_contiguous(a));
6236
0
    GGML_ASSERT(ggml_is_contiguous(b));
6237
6238
0
    GGML_ASSERT(lower && left && !uni); // TODO: support other variants
6239
6240
0
    struct ggml_tensor * result = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, b->ne[0], b->ne[1], b->ne[2], b->ne[3]);
6241
6242
0
    result->op     = GGML_OP_SOLVE_TRI;
6243
0
    result->src[0] = a;
6244
0
    result->src[1] = b;
6245
6246
0
    return result;
6247
0
}
6248
6249
// ggml_gated_delta_net
6250
6251
struct ggml_tensor * ggml_gated_delta_net(
6252
        struct ggml_context * ctx,
6253
        struct ggml_tensor  * q,
6254
        struct ggml_tensor  * k,
6255
        struct ggml_tensor  * v,
6256
        struct ggml_tensor  * g,
6257
        struct ggml_tensor  * beta,
6258
        struct ggml_tensor  * state,
6259
0
        int64_t               K) {
6260
0
    GGML_ASSERT(ggml_is_contiguous_rows(q));
6261
0
    GGML_ASSERT(ggml_is_contiguous_rows(k));
6262
0
    GGML_ASSERT(ggml_is_contiguous_rows(v));
6263
0
    GGML_ASSERT(ggml_is_contiguous(g));
6264
0
    GGML_ASSERT(ggml_is_contiguous(beta));
6265
0
    GGML_ASSERT(ggml_is_contiguous(state));
6266
6267
0
    GGML_ASSERT(q->type == GGML_TYPE_F32);
6268
0
    GGML_ASSERT(k->type == GGML_TYPE_F32);
6269
0
    GGML_ASSERT(v->type == GGML_TYPE_F32);
6270
0
    GGML_ASSERT(g->type == GGML_TYPE_F32);
6271
0
    GGML_ASSERT(beta->type == GGML_TYPE_F32);
6272
0
    GGML_ASSERT(state->type == GGML_TYPE_F32);
6273
6274
0
    const int64_t S_v      = v->ne[0];
6275
0
    const int64_t H        = v->ne[1];
6276
0
    const int64_t n_tokens = v->ne[2];
6277
0
    const int64_t n_seqs   = v->ne[3];
6278
6279
    // gate: scalar [1, H, T, B] or vector [S_v, H, T, B] (KDA)
6280
0
    GGML_ASSERT(g->ne[0] == 1 || g->ne[0] == S_v);
6281
0
    GGML_ASSERT(beta->ne[0] == 1);
6282
6283
    // state holds the initial state s0 only: [S_v, S_v, H, n_seqs]. K (snapshot slot count) is an op param.
6284
0
    GGML_ASSERT(state->ne[0] == S_v);
6285
0
    GGML_ASSERT(state->ne[1] == S_v);
6286
0
    GGML_ASSERT(state->ne[2] == H);
6287
0
    GGML_ASSERT(state->ne[3] == n_seqs);
6288
0
    GGML_ASSERT(K >= 1);
6289
0
    const int64_t state_rows = K * S_v * n_seqs;
6290
0
    const int64_t ne[4] = { S_v * H, n_tokens * n_seqs + state_rows, 1, 1 };
6291
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
6292
6293
0
    ggml_set_op_params_i32(result, 0, (int32_t) K);
6294
6295
0
    result->op     = GGML_OP_GATED_DELTA_NET;
6296
0
    result->src[0] = q;
6297
0
    result->src[1] = k;
6298
0
    result->src[2] = v;
6299
0
    result->src[3] = g;
6300
0
    result->src[4] = beta;
6301
0
    result->src[5] = state;
6302
6303
0
    return result;
6304
0
}
6305
6306
// ggml_lightning_indexer
6307
6308
struct ggml_tensor * ggml_lightning_indexer(
6309
        struct ggml_context * ctx,
6310
        struct ggml_tensor  * q,
6311
        struct ggml_tensor  * k,
6312
        struct ggml_tensor  * weights,
6313
0
        struct ggml_tensor  * mask) {
6314
6315
0
    GGML_ASSERT(       q->type == GGML_TYPE_F32);
6316
0
    GGML_ASSERT( weights->type == GGML_TYPE_F32);
6317
0
    GGML_ASSERT(    mask->type == GGML_TYPE_F16);
6318
0
    GGML_ASSERT(      q->ne[0] == k->ne[0]);
6319
0
    GGML_ASSERT(   mask->ne[0] == k->ne[2]);
6320
0
    GGML_ASSERT(      q->ne[1] == weights->ne[0]);
6321
0
    GGML_ASSERT(      k->ne[1] == 1);
6322
0
    GGML_ASSERT(   mask->ne[1] == q->ne[2]);
6323
0
    GGML_ASSERT(      q->ne[2] == weights->ne[1]);
6324
0
    GGML_ASSERT(weights->ne[2] == 1);
6325
0
    GGML_ASSERT(   mask->ne[2] == 1);
6326
0
    GGML_ASSERT(      q->ne[3] == k->ne[3]);
6327
0
    GGML_ASSERT(      k->ne[3] == weights->ne[3]);
6328
0
    GGML_ASSERT(weights->ne[3] % mask->ne[3] == 0);
6329
6330
0
    int64_t ne[4] = { k->ne[2], q->ne[2], 1, q->ne[3] };
6331
0
    struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
6332
6333
0
    result->op   = GGML_OP_LIGHTNING_INDEXER;
6334
0
    result->src[0] = q;
6335
0
    result->src[1] = k;
6336
0
    result->src[2] = weights;
6337
0
    result->src[3] = mask;
6338
6339
0
    return result;
6340
0
}
6341
6342
////////////////////////////////////////////////////////////////////////////////
6343
6344
0
struct ggml_hash_set ggml_hash_set_new(size_t size) {
6345
0
    size = ggml_hash_size(size);
6346
0
    struct ggml_hash_set result;
6347
0
    result.size = size;
6348
0
    result.keys = GGML_MALLOC(sizeof(struct ggml_tensor *) * size);
6349
0
    result.used = GGML_CALLOC(ggml_bitset_size(size), sizeof(ggml_bitset_t));
6350
0
    return result;
6351
0
}
6352
6353
0
void ggml_hash_set_reset(struct ggml_hash_set * hash_set) {
6354
0
    memset(hash_set->used, 0, sizeof(ggml_bitset_t) * ggml_bitset_size(hash_set->size));
6355
0
}
6356
6357
0
void ggml_hash_set_free(struct ggml_hash_set * hash_set) {
6358
0
    GGML_FREE(hash_set->used);
6359
0
    GGML_FREE(hash_set->keys);
6360
0
}
6361
6362
0
size_t ggml_hash_size(size_t min_sz) {
6363
    // next primes after powers of two
6364
0
    static const size_t primes[] = {
6365
0
        2, 3, 5, 11, 17, 37, 67, 131, 257, 521, 1031,
6366
0
        2053, 4099, 8209, 16411, 32771, 65537, 131101,
6367
0
        262147, 524309, 1048583, 2097169, 4194319, 8388617,
6368
0
        16777259, 33554467, 67108879, 134217757, 268435459,
6369
0
        536870923, 1073741827, 2147483659
6370
0
    };
6371
0
    static const size_t n_primes = sizeof(primes)/sizeof(primes[0]);
6372
6373
    // find the smallest prime that is larger or equal than min_sz
6374
0
    size_t l = 0;
6375
0
    size_t r = n_primes;
6376
0
    while (l < r) {
6377
0
        size_t m = (l + r)/2;
6378
0
        if (primes[m] < min_sz) {
6379
0
            l = m + 1;
6380
0
        } else {
6381
0
            r = m;
6382
0
        }
6383
0
    }
6384
0
    size_t sz = l < n_primes ? primes[l] : min_sz | 1;
6385
0
    return sz;
6386
0
}
6387
6388
struct hash_map {
6389
    struct ggml_hash_set set;
6390
    struct ggml_tensor ** vals;
6391
};
6392
6393
0
static struct hash_map * ggml_new_hash_map(size_t size) {
6394
0
    struct hash_map * result = GGML_MALLOC(sizeof(struct hash_map));
6395
0
    result->set = ggml_hash_set_new(size);
6396
0
    result->vals = GGML_CALLOC(result->set.size, sizeof(struct ggml_tensor *));
6397
0
    return result;
6398
0
}
6399
6400
0
static void ggml_hash_map_free(struct hash_map * map) {
6401
0
    ggml_hash_set_free(&map->set);
6402
0
    GGML_FREE(map->vals);
6403
0
    GGML_FREE(map);
6404
0
}
6405
6406
// utility functions to change gradients
6407
// isrc is the index of tensor in cgraph->visited_has_set.keys
6408
// the corresponding gradient (accumulators) are also at position isrc
6409
// if tensor has a gradient accumulator, modify that accumulator in-place
6410
// else if there is no gradient for tensor, set the corresponding value
6411
// else, just add/subtract/etc. the gradients
6412
6413
static void ggml_add_or_set(
6414
        struct ggml_context * ctx,
6415
        struct ggml_cgraph  * cgraph,
6416
        size_t                isrc,
6417
0
        struct ggml_tensor  * tensor) {
6418
0
    struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
6419
0
    GGML_ASSERT(src);
6420
0
    if (cgraph->grads[isrc]) {
6421
0
        cgraph->grads[isrc] = ggml_add_impl(ctx, cgraph->grads[isrc], tensor, /*inplace =*/ cgraph->grad_accs[isrc]);
6422
0
    } else {
6423
0
        cgraph->grads[isrc] = tensor;
6424
0
    }
6425
0
    ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
6426
0
    ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
6427
0
}
6428
6429
static void ggml_acc_or_set(
6430
        struct ggml_context * ctx,
6431
        struct ggml_cgraph  * cgraph,
6432
        size_t                isrc,
6433
        struct ggml_tensor  * tensor,
6434
        const  size_t         nb1,
6435
        const  size_t         nb2,
6436
        const  size_t         nb3,
6437
0
        const  size_t         offset) {
6438
0
    struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
6439
0
    GGML_ASSERT(src);
6440
0
    if (cgraph->grads[isrc]) {
6441
0
        cgraph->grads[isrc] = ggml_acc_impl(ctx, cgraph->grads[isrc], tensor, nb1, nb2, nb3, offset, cgraph->grad_accs[isrc]);
6442
0
    } else {
6443
0
        struct ggml_tensor * a_zero = ggml_scale(ctx, src, 0.0f); // FIXME this is going to produce NaN if a contains inf/NaN
6444
0
        cgraph->grads[isrc] = ggml_acc_impl(ctx, a_zero, tensor, nb1, nb2, nb3, offset, false);
6445
0
    }
6446
0
    ggml_format_name(cgraph->grads[isrc], "grad for %s", cgraph->visited_hash_set.keys[isrc]->name);
6447
0
    ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
6448
0
}
6449
6450
static void ggml_add1_or_set(
6451
        struct ggml_context * ctx,
6452
        struct ggml_cgraph  * cgraph,
6453
        size_t                isrc,
6454
0
        struct ggml_tensor  * tensor) {
6455
0
    struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
6456
0
    GGML_ASSERT(src);
6457
0
    if (cgraph->grads[isrc]) {
6458
0
        cgraph->grads[isrc] = ggml_add1_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
6459
0
    } else {
6460
0
        cgraph->grads[isrc] = ggml_repeat(ctx, tensor, src);
6461
0
    }
6462
0
    ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
6463
0
    ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
6464
0
}
6465
6466
static void ggml_sub_or_set(
6467
        struct ggml_context * ctx,
6468
        struct ggml_cgraph  * cgraph,
6469
        size_t                isrc,
6470
0
        struct ggml_tensor  * tensor) {
6471
0
    struct ggml_tensor * src = cgraph->visited_hash_set.keys[isrc];
6472
0
    GGML_ASSERT(src);
6473
0
    if (cgraph->grads[isrc]) {
6474
0
        cgraph->grads[isrc] = ggml_sub_impl(ctx, cgraph->grads[isrc], tensor, cgraph->grad_accs[isrc]);
6475
0
    } else {
6476
0
        cgraph->grads[isrc] = ggml_neg(ctx, tensor);
6477
0
    }
6478
0
    ggml_format_name(cgraph->grads[isrc], "grad for %s", src->name);
6479
0
    ggml_build_forward_expand(cgraph, cgraph->grads[isrc]);
6480
0
}
6481
6482
static void ggml_compute_backward(
6483
0
        struct ggml_context * ctx, struct ggml_cgraph * cgraph, int i, const bool * grads_needed) {
6484
0
    struct ggml_tensor * tensor = cgraph->nodes[i];
6485
0
    struct ggml_tensor * grad   = ggml_graph_get_grad(cgraph, tensor);
6486
6487
0
    if (!grad) {
6488
0
        return;
6489
0
    }
6490
6491
0
    struct ggml_tensor * src0 = tensor->src[0];
6492
0
    struct ggml_tensor * src1 = tensor->src[1];
6493
0
    struct ggml_tensor * src2 = tensor->src[2];
6494
0
    struct ggml_hash_set * hash_set = &cgraph->visited_hash_set;
6495
0
    const size_t isrc0 = src0 ? ggml_hash_find(hash_set, src0) : (size_t) -1;
6496
0
    const size_t isrc1 = src1 ? ggml_hash_find(hash_set, src1) : (size_t) -1;
6497
0
    const size_t isrc2 = src2 ? ggml_hash_find(hash_set, src2) : (size_t) -1;
6498
0
    const bool src0_needs_grads = src0 && isrc0 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc0) && grads_needed[isrc0];
6499
0
    const bool src1_needs_grads = src1 && isrc1 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc1) && grads_needed[isrc1];
6500
0
    const bool src2_needs_grads = src2 && isrc2 != GGML_HASHSET_FULL && ggml_bitset_get(hash_set->used, isrc2) && grads_needed[isrc2];
6501
6502
0
    switch (tensor->op) {
6503
0
        case GGML_OP_DUP: {
6504
0
            if (src0_needs_grads) {
6505
0
                ggml_add_or_set(ctx, cgraph, isrc0, grad);
6506
0
            }
6507
0
        } break;
6508
0
        case GGML_OP_ADD: {
6509
0
            if (src0_needs_grads) {
6510
0
                ggml_add_or_set(ctx, cgraph, isrc0, grad);
6511
0
            }
6512
0
            if (src1_needs_grads) {
6513
0
                struct ggml_tensor * tmp = grad;
6514
0
                if (!ggml_are_same_shape(src0, src1)) {
6515
0
                    tmp = ggml_repeat_back(ctx, tmp, src1);
6516
0
                }
6517
0
                ggml_add_or_set(ctx, cgraph, isrc1, tmp);
6518
0
            }
6519
0
        } break;
6520
0
        case GGML_OP_ADD1: {
6521
0
            if (src0_needs_grads) {
6522
0
                ggml_add_or_set(ctx, cgraph, isrc0, grad);
6523
0
            }
6524
0
            if (src1_needs_grads) {
6525
0
                ggml_add_or_set(ctx, cgraph, isrc1, ggml_mean(ctx, grad)); // TODO: should probably be sum instead of mean
6526
0
            }
6527
0
        } break;
6528
0
        case GGML_OP_ACC: {
6529
0
            if (src0_needs_grads) {
6530
0
                ggml_add_or_set(ctx, cgraph, isrc0, grad);
6531
0
            }
6532
0
            if (src1_needs_grads) {
6533
0
                const size_t nb1    = ((int32_t *) tensor->op_params)[0];
6534
0
                const size_t nb2    = ((int32_t *) tensor->op_params)[1];
6535
0
                const size_t nb3    = ((int32_t *) tensor->op_params)[2];
6536
0
                const size_t offset = ((int32_t *) tensor->op_params)[3];
6537
6538
0
                struct ggml_tensor * tensor_grad_view = ggml_view_4d(ctx,
6539
0
                    grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
6540
0
                    nb1, nb2, nb3, offset);
6541
6542
0
                ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
6543
0
            }
6544
0
        } break;
6545
0
        case GGML_OP_SUB: {
6546
0
            if (src0_needs_grads) {
6547
0
                ggml_add_or_set(ctx, cgraph, isrc0, grad);
6548
0
            }
6549
0
            if (src1_needs_grads) {
6550
0
                ggml_sub_or_set(ctx, cgraph, isrc1, grad);
6551
0
            }
6552
0
        } break;
6553
0
        case GGML_OP_MUL: {
6554
0
            if (src0_needs_grads) {
6555
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, src1));
6556
0
            }
6557
0
            if (src1_needs_grads) {
6558
0
                struct ggml_tensor * tmp = ggml_mul(ctx, src0, grad);
6559
0
                if (!ggml_are_same_shape(src0, src1)) {
6560
0
                    tmp = ggml_repeat_back(ctx, tmp, src1);
6561
0
                }
6562
0
                ggml_add_or_set(ctx, cgraph, isrc1, tmp);
6563
0
            }
6564
0
        } break;
6565
0
        case GGML_OP_DIV: {
6566
0
            if (src0_needs_grads) {
6567
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src1));
6568
0
            }
6569
0
            if (src1_needs_grads) {
6570
0
                ggml_sub_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, grad, ggml_div(ctx, tensor, src1)));
6571
0
            }
6572
0
        } break;
6573
0
        case GGML_OP_SQR: {
6574
0
            if (src0_needs_grads) {
6575
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_mul(ctx, src0, grad), 2.0f));
6576
0
            }
6577
0
        } break;
6578
0
        case GGML_OP_SQRT: {
6579
0
            if (src0_needs_grads) {
6580
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale(ctx, ggml_div(ctx, grad, tensor), 0.5f));
6581
0
            }
6582
0
        } break;
6583
0
        case GGML_OP_LOG: {
6584
0
            if (src0_needs_grads) {
6585
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_div(ctx, grad, src0));
6586
0
            }
6587
0
        } break;
6588
0
        case GGML_OP_SIN: {
6589
0
            if (src0_needs_grads) {
6590
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_cos(ctx, src0)));
6591
0
            }
6592
0
        } break;
6593
0
        case GGML_OP_COS: {
6594
0
            if (src0_needs_grads) {
6595
0
                ggml_sub_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sin(ctx, src0)));
6596
0
            }
6597
0
        } break;
6598
0
        case GGML_OP_SUM: {
6599
0
            if (src0_needs_grads) {
6600
0
                ggml_add1_or_set(ctx, cgraph, isrc0, grad);
6601
0
            }
6602
0
        } break;
6603
0
        case GGML_OP_SUM_ROWS: {
6604
0
            if (src0_needs_grads) {
6605
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
6606
0
            }
6607
0
        } break;
6608
0
        case GGML_OP_MEAN: {
6609
0
            if (src0_needs_grads) {
6610
0
                ggml_add1_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, 1.0f/src0->ne[0], 0.0, false));
6611
0
            }
6612
0
        } break;
6613
0
        case GGML_OP_REPEAT: {
6614
0
            if (src0_needs_grads) {
6615
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat_back(ctx, grad, src0));
6616
0
            }
6617
0
        } break;
6618
0
        case GGML_OP_REPEAT_BACK: {
6619
0
            if (src0_needs_grads) {
6620
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_repeat(ctx, grad, src0));
6621
0
            }
6622
0
        } break;
6623
0
        case GGML_OP_RMS_NORM: {
6624
0
            if (src0_needs_grads) {
6625
0
                float eps;
6626
0
                memcpy(&eps, tensor->op_params, sizeof(float));
6627
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_rms_norm_back(ctx, grad, src0, eps));
6628
0
            }
6629
0
        } break;
6630
0
        case GGML_OP_MUL_MAT: {
6631
            // https://cs231n.github.io/optimization-2/#staged
6632
            // # forward pass
6633
            // s0 = np.random.randn(5, 10)
6634
            // s1 = np.random.randn(10, 3)
6635
            // t = s0.dot(s1)
6636
6637
            // # now suppose we had the gradient on t from above in the circuit
6638
            // dt = np.random.randn(*t.shape) # same shape as t
6639
            // ds0 = dt.dot(s1.T) #.T gives the transpose of the matrix
6640
            // ds1 = t.T.dot(dt)
6641
6642
            // tensor.shape [m,p,qq,rr]
6643
            // src0.shape   [n,m,q1,r1]
6644
            // src1.shape   [n,p,qq,rr]
6645
6646
0
            if (src0_needs_grads) {
6647
0
                GGML_ASSERT(grad->ne[2] == src1->ne[2]);
6648
0
                GGML_ASSERT(grad->ne[3] == src1->ne[3]);
6649
0
                struct ggml_tensor * tmp =
6650
0
                    ggml_out_prod(ctx, // [n,m,qq,rr]
6651
0
                        src1,          // [n,p,qq,rr]
6652
0
                        grad);         // [m,p,qq,rr]
6653
0
                if (!ggml_are_same_shape(tmp, src0)) {
6654
0
                    GGML_ASSERT(tmp->ne[0] == src0->ne[0]);
6655
0
                    GGML_ASSERT(tmp->ne[1] == src0->ne[1]);
6656
0
                    GGML_ASSERT(tmp->ne[3] == 1);
6657
6658
0
                    const int64_t nr2 = tmp->ne[2] / src0->ne[2];
6659
0
                    const size_t nb2 = tmp->nb[2] * nr2;
6660
0
                    const size_t nb3 = tmp->nb[2];
6661
6662
0
                    tmp = ggml_view_4d(ctx, tmp, src0->ne[0], src0->ne[1], src0->ne[2], nr2, tmp->nb[1], nb2, nb3, 0);
6663
0
                    tmp = ggml_repeat_back(ctx, tmp, src0);
6664
0
                }
6665
0
                ggml_add_or_set(ctx, cgraph, isrc0, tmp);
6666
0
            }
6667
0
            if (src1_needs_grads) {
6668
0
                ggml_add_or_set(ctx, cgraph, isrc1,
6669
                        // ggml_mul_mat(ctx,                   // [n,p,qq,rr]
6670
                        //     ggml_cont(ctx,                  // [m,n,q1,r1]
6671
                        //         ggml_transpose(ctx, src0)), // [m,n,q1,r1]
6672
                        //     grad),                          // [m,p,qq,rr]
6673
6674
                        // when src0 is bigger than tensor->grad (this is mostly the case in llama),
6675
                        // avoid transpose of src0, rather transpose smaller tensor->grad
6676
                        // and then use ggml_out_prod
6677
0
                        ggml_out_prod(ctx,      // [n,p,qq,rr]
6678
0
                            src0,               // [n,m,q1,r1]
6679
0
                            ggml_transpose(ctx, // [p,m,qq,rr]
6680
0
                                grad)));        // [m,p,qq,rr]
6681
0
            }
6682
0
        } break;
6683
0
        case GGML_OP_SCALE: {
6684
0
            if (src0_needs_grads) {
6685
0
                float s;
6686
0
                memcpy(&s, tensor->op_params, sizeof(float));
6687
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_scale_impl(ctx, grad, s, 0.0, false));
6688
0
            }
6689
0
        } break;
6690
0
        case GGML_OP_SET: {
6691
0
            const size_t nb1    = ((const int32_t *) tensor->op_params)[0];
6692
0
            const size_t nb2    = ((const int32_t *) tensor->op_params)[1];
6693
0
            const size_t nb3    = ((const int32_t *) tensor->op_params)[2];
6694
0
            const size_t offset = ((const int32_t *) tensor->op_params)[3];
6695
6696
0
            struct ggml_tensor * tensor_grad_view = NULL;
6697
6698
0
            if (src0_needs_grads || src1_needs_grads) {
6699
0
                GGML_ASSERT(src0->type == tensor->type);
6700
0
                GGML_ASSERT(!cgraph->grads[isrc0] ||                      cgraph->grads[isrc0]->type == grad->type);
6701
0
                GGML_ASSERT(!cgraph->grads[isrc1] || !src1_needs_grads || cgraph->grads[isrc1]->type == grad->type);
6702
6703
0
                tensor_grad_view = ggml_view_4d(ctx,
6704
0
                    grad, src1->ne[0], src1->ne[1], src1->ne[2], src1->ne[3],
6705
0
                    nb1, nb2, nb3, offset);
6706
0
            }
6707
6708
0
            if (src0_needs_grads) {
6709
0
                struct ggml_tensor * tmp = ggml_neg(ctx, tensor_grad_view);
6710
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_acc_impl(ctx, grad, tmp, nb1, nb2, nb3, offset, false));
6711
0
            }
6712
6713
0
            if (src1_needs_grads) {
6714
0
                ggml_add_or_set(ctx, cgraph, isrc1, ggml_reshape(ctx, ggml_cont(ctx, tensor_grad_view), src1));
6715
0
            }
6716
0
        } break;
6717
0
        case GGML_OP_CPY: {
6718
            // cpy overwrites value of src1 by src0 and returns view(src1)
6719
            // the overwriting is mathematically equivalent to:
6720
            // tensor = src0 * 1 + src1 * 0
6721
0
            if (src0_needs_grads) {
6722
                // dsrc0 = dtensor * 1
6723
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_reshape(ctx, grad, src0));
6724
0
            }
6725
0
            if (src1_needs_grads) {
6726
                // dsrc1 = dtensor * 0 -> noop
6727
0
            }
6728
0
        } break;
6729
0
        case GGML_OP_CONT: {
6730
            // same as cpy
6731
0
            if (src0_needs_grads) {
6732
0
                GGML_ASSERT(!cgraph->grads[isrc0] || ggml_is_contiguous(cgraph->grads[isrc0]));
6733
0
                GGML_ASSERT(ggml_is_contiguous(grad));
6734
0
                GGML_ASSERT(ggml_nelements(tensor) == ggml_nelements(src0));
6735
0
                ggml_add_or_set(ctx, cgraph, isrc0,
6736
0
                    ggml_are_same_shape(tensor, src0) ? grad : ggml_reshape(ctx, grad, src0));
6737
0
            }
6738
0
        } break;
6739
0
        case GGML_OP_RESHAPE: {
6740
0
            if (src0_needs_grads) {
6741
0
                struct ggml_tensor * grad_cont = ggml_is_contiguous(grad) ? grad : ggml_cont(ctx, grad);
6742
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_reshape(ctx, grad_cont, src0));
6743
0
            }
6744
0
        } break;
6745
0
        case GGML_OP_VIEW: {
6746
0
            if (src0_needs_grads) {
6747
0
                size_t offset;
6748
6749
0
                memcpy(&offset, tensor->op_params, sizeof(offset));
6750
6751
0
                size_t nb1 = tensor->nb[1];
6752
0
                size_t nb2 = tensor->nb[2];
6753
0
                size_t nb3 = tensor->nb[3];
6754
6755
0
                if (cgraph->grads[isrc0] && src0->type != cgraph->grads[isrc0]->type) {
6756
                    // gradient is typically F32, but src0 could be other type
6757
0
                    size_t ng = ggml_element_size(cgraph->grads[isrc0]);
6758
0
                    size_t n0 = ggml_element_size(src0);
6759
0
                    GGML_ASSERT(offset % n0 == 0);
6760
0
                    GGML_ASSERT(nb1 % n0 == 0);
6761
0
                    GGML_ASSERT(nb2 % n0 == 0);
6762
0
                    GGML_ASSERT(nb3 % n0 == 0);
6763
0
                    offset = (offset / n0) * ng;
6764
0
                    nb1 = (nb1 / n0) * ng;
6765
0
                    nb2 = (nb2 / n0) * ng;
6766
0
                    nb3 = (nb3 / n0) * ng;
6767
0
                }
6768
6769
0
                ggml_acc_or_set(ctx, cgraph, isrc0, grad, nb1, nb2, nb3, offset);
6770
0
            }
6771
0
        } break;
6772
0
        case GGML_OP_PERMUTE: {
6773
0
            if (src0_needs_grads) {
6774
0
                const int32_t * axes = (const int32_t *) tensor->op_params;
6775
0
                const int axis0 = axes[0] & 0x3;
6776
0
                const int axis1 = axes[1] & 0x3;
6777
0
                const int axis2 = axes[2] & 0x3;
6778
0
                const int axis3 = axes[3] & 0x3;
6779
0
                int axb[4] = {0,0,0,0}; // axes backward
6780
0
                axb[axis0] = 0;
6781
0
                axb[axis1] = 1;
6782
0
                axb[axis2] = 2;
6783
0
                axb[axis3] = 3;
6784
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_permute(ctx, grad, axb[0], axb[1], axb[2], axb[3]));
6785
0
            }
6786
0
        } break;
6787
0
        case GGML_OP_TRANSPOSE: {
6788
0
            if (src0_needs_grads) {
6789
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_transpose(ctx, grad));
6790
0
            }
6791
0
        } break;
6792
0
        case GGML_OP_GET_ROWS: {
6793
0
            if (src0_needs_grads) {
6794
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_get_rows_back(ctx, grad, src1, src0));
6795
0
            }
6796
0
            if (src1_needs_grads) {
6797
                // noop
6798
0
            }
6799
0
        } break;
6800
0
        case GGML_OP_DIAG_MASK_INF: {
6801
0
            if (src0_needs_grads) {
6802
                /* ggml_diag_mask_inf_impl() shouldn't be here */
6803
                /* ref:  https://github.com/ggml-org/llama.cpp/pull/4203#discussion_r1412377992 */
6804
0
                const int n_past = ((const int32_t *) tensor->op_params)[0];
6805
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
6806
0
            }
6807
0
        } break;
6808
0
        case GGML_OP_DIAG_MASK_ZERO: {
6809
0
            if (src0_needs_grads) {
6810
0
                const int n_past = ((const int32_t *) tensor->op_params)[0];
6811
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_diag_mask_zero_impl(ctx, grad, n_past, false));
6812
0
            }
6813
0
        } break;
6814
0
        case GGML_OP_SOFT_MAX: {
6815
0
            if (src0_needs_grads) {
6816
0
                float scale    = 1.0f;
6817
0
                float max_bias = 0.0f;
6818
6819
0
                memcpy(&scale,    (const float *) tensor->op_params + 0, sizeof(float));
6820
0
                memcpy(&max_bias, (const float *) tensor->op_params + 1, sizeof(float));
6821
6822
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_soft_max_ext_back(ctx, grad, tensor, scale, max_bias));
6823
0
            }
6824
0
            GGML_ASSERT((!src1 || !src1_needs_grads) && "backward pass for softmax mask not implemented");
6825
0
        } break;
6826
0
        case GGML_OP_ROPE: {
6827
0
            if (src0_needs_grads) {
6828
                //const int n_past = ((int32_t *) tensor->op_params)[0];
6829
0
                const int n_dims     = ((const int32_t *) tensor->op_params)[1];
6830
0
                const int mode       = ((const int32_t *) tensor->op_params)[2];
6831
                //const int n_ctx      = ((int32_t *) tensor->op_params)[3];
6832
0
                const int n_ctx_orig = ((const int32_t *) tensor->op_params)[4];
6833
0
                float freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow;
6834
0
                int sections[4] = {0, 0, 0, 0};
6835
6836
0
                memcpy(&freq_base,   (const float *) tensor->op_params +  5, sizeof(float));
6837
0
                memcpy(&freq_scale,  (const float *) tensor->op_params +  6, sizeof(float));
6838
0
                memcpy(&ext_factor,  (const float *) tensor->op_params +  7, sizeof(float));
6839
0
                memcpy(&attn_factor, (const float *) tensor->op_params +  8, sizeof(float));
6840
0
                memcpy(&beta_fast,   (const float *) tensor->op_params +  9, sizeof(float));
6841
0
                memcpy(&beta_slow,   (const float *) tensor->op_params + 10, sizeof(float));
6842
0
                memcpy(&sections,                    tensor->op_params + 11, sizeof(sections));
6843
6844
0
                struct ggml_tensor * rope_back = grad->ne[2] == src1->ne[0] ?
6845
0
                    ggml_rope_ext_back(ctx, grad, src1, src2, n_dims,
6846
0
                        mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow) :
6847
0
                    ggml_rope_multi_back(ctx, grad, src1, src2, n_dims, sections,
6848
0
                        mode, n_ctx_orig, freq_base, freq_scale, ext_factor, attn_factor, beta_fast, beta_slow);
6849
0
                ggml_add_or_set(ctx, cgraph, isrc0, rope_back);
6850
0
            }
6851
0
            GGML_ASSERT((!src2 || !src2_needs_grads) && "gradients for freq factors not implemented");
6852
0
        } break;
6853
0
        case GGML_OP_IM2COL: {
6854
0
            if (src1_needs_grads) {
6855
0
                const int32_t s0    = ggml_get_op_params_i32(tensor, 0);
6856
0
                const int32_t s1    = ggml_get_op_params_i32(tensor, 1);
6857
0
                const int32_t p0    = ggml_get_op_params_i32(tensor, 2);
6858
0
                const int32_t p1    = ggml_get_op_params_i32(tensor, 3);
6859
0
                const int32_t d0    = ggml_get_op_params_i32(tensor, 4);
6860
0
                const int32_t d1    = ggml_get_op_params_i32(tensor, 5);
6861
0
                const bool    is_2D = ggml_get_op_params_i32(tensor, 6) == 1;
6862
6863
0
                ggml_add_or_set(ctx, cgraph, isrc1, ggml_im2col_back(ctx, grad, src0, src1->ne, s0, s1, p0, p1, d0, d1, is_2D));
6864
0
            }
6865
0
        } break;
6866
0
        case GGML_OP_POOL_2D: {
6867
0
            if (src0_needs_grads) {
6868
0
                const enum ggml_op_pool op = ggml_get_op_params_i32(tensor, 0);
6869
0
                const      int32_t      k0 = ggml_get_op_params_i32(tensor, 1);
6870
0
                const      int32_t      k1 = ggml_get_op_params_i32(tensor, 2);
6871
0
                const      int32_t      s0 = ggml_get_op_params_i32(tensor, 3);
6872
0
                const      int32_t      s1 = ggml_get_op_params_i32(tensor, 4);
6873
0
                const      int32_t      p0 = ggml_get_op_params_i32(tensor, 5);
6874
0
                const      int32_t      p1 = ggml_get_op_params_i32(tensor, 6);
6875
6876
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_pool_2d_back(ctx, grad, src0, op, k0, k1, s0, s1, p0, p1));
6877
0
            }
6878
0
        } break;
6879
0
        case GGML_OP_WIN_PART:
6880
0
        case GGML_OP_WIN_UNPART:
6881
0
        case GGML_OP_UNARY: {
6882
0
            switch (ggml_get_unary_op(tensor)) {
6883
0
                case GGML_UNARY_OP_ABS: {
6884
0
                    if (src0_needs_grads) {
6885
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_sgn(ctx, src0), grad));
6886
0
                    }
6887
0
                } break;
6888
0
                case GGML_UNARY_OP_SGN: {
6889
                    // noop
6890
0
                } break;
6891
0
                case GGML_UNARY_OP_NEG: {
6892
0
                    if (src0_needs_grads) {
6893
0
                        ggml_sub_or_set(ctx, cgraph, isrc0, grad);
6894
0
                    }
6895
0
                } break;
6896
0
                case GGML_UNARY_OP_STEP: {
6897
                    // noop
6898
0
                } break;
6899
0
                case GGML_UNARY_OP_RELU: {
6900
0
                    if (src0_needs_grads) {
6901
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, ggml_step(ctx, src0), grad));
6902
0
                    }
6903
0
                } break;
6904
0
                case GGML_UNARY_OP_SILU: {
6905
0
                    if (src0_needs_grads) {
6906
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, grad, src0));
6907
0
                    }
6908
0
                } break;
6909
0
                case GGML_UNARY_OP_EXP: {
6910
0
                    if (src0_needs_grads) {
6911
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, tensor, grad));
6912
0
                    }
6913
0
                } break;
6914
0
                case GGML_UNARY_OP_EXPM1: {
6915
0
                    if (src0_needs_grads) {
6916
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_exp(ctx, src0)));
6917
0
                    }
6918
0
                } break;
6919
0
                case GGML_UNARY_OP_SOFTPLUS: {
6920
0
                    if (src0_needs_grads) {
6921
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_mul(ctx, grad, ggml_sigmoid(ctx, src0)));
6922
0
                    }
6923
0
                } break;
6924
0
                default: {
6925
0
                    fprintf(stderr, "%s: unsupported unary op for backward pass: %s\n",
6926
0
                        __func__, ggml_unary_op_name(ggml_get_unary_op(tensor)));
6927
0
                    GGML_ABORT("fatal error");
6928
0
                } //break;
6929
0
            }
6930
0
        } break;
6931
0
        case GGML_OP_CROSS_ENTROPY_LOSS: {
6932
0
            if (src0_needs_grads) {
6933
0
                ggml_add_or_set(ctx, cgraph, isrc0, ggml_cross_entropy_loss_back(ctx, grad, src0, src1));
6934
0
            }
6935
0
            GGML_ASSERT(!src1_needs_grads && "backward pass for labels not implemented");
6936
0
        } break;
6937
0
        case GGML_OP_GLU: {
6938
0
            switch (ggml_get_glu_op(tensor)) {
6939
0
                case GGML_GLU_OP_SWIGLU: {
6940
0
                    if (src0_needs_grads) {
6941
0
                        GGML_ASSERT(src1 && "backward pass only implemented for split swiglu");
6942
0
                        ggml_add_or_set(ctx, cgraph, isrc0, ggml_silu_back(ctx, ggml_mul(ctx, grad, src1), src0));
6943
0
                    }
6944
0
                    if (src1_needs_grads) {
6945
0
                        ggml_add_or_set(ctx, cgraph, isrc1, ggml_mul(ctx, ggml_silu(ctx, src0), grad));
6946
0
                    }
6947
0
                } break;
6948
0
                default: {
6949
0
                    GGML_ABORT("unsupported glu op for backward pass: %s", ggml_glu_op_name(ggml_get_glu_op(tensor)));
6950
0
                } //break;
6951
0
            }
6952
0
        } break;
6953
0
        case GGML_OP_NONE: {
6954
            // noop
6955
0
        } break;
6956
0
        case GGML_OP_COUNT:
6957
0
        default: {
6958
0
            GGML_ABORT("%s: unsupported ggml op for backward pass: %s\n", __func__, ggml_op_name(tensor->op));
6959
0
        } //break;
6960
0
    }
6961
6962
0
    GGML_ASSERT(!src0_needs_grads || ggml_are_same_shape(src0, cgraph->grads[isrc0]));
6963
0
    GGML_ASSERT(!src1_needs_grads || ggml_are_same_shape(src1, cgraph->grads[isrc1]));
6964
0
    GGML_ASSERT(!src2_needs_grads || ggml_are_same_shape(src2, cgraph->grads[isrc2]));
6965
0
}
6966
6967
0
static size_t ggml_visit_parents_graph(struct ggml_cgraph * cgraph, struct ggml_tensor * node, bool compute) {
6968
0
    if (node->op != GGML_OP_NONE && compute) {
6969
0
        node->flags |= GGML_TENSOR_FLAG_COMPUTE;
6970
0
    }
6971
6972
0
    const size_t node_hash_pos = ggml_hash_find(&cgraph->visited_hash_set, node);
6973
0
    GGML_ASSERT(node_hash_pos != GGML_HASHSET_FULL);
6974
6975
0
    if (ggml_bitset_get(cgraph->visited_hash_set.used, node_hash_pos)) {
6976
        // already visited
6977
6978
0
        if (compute) {
6979
            // update the compute flag regardless
6980
0
            for (int i = 0; i < GGML_MAX_SRC; ++i) {
6981
0
                struct ggml_tensor * src = node->src[i];
6982
0
                if (src && ((src->flags & GGML_TENSOR_FLAG_COMPUTE) == 0)) {
6983
0
                    ggml_visit_parents_graph(cgraph, src, true);
6984
0
                }
6985
0
            }
6986
0
        }
6987
6988
0
        return node_hash_pos;
6989
0
    }
6990
6991
    // This is the first time we see this node in the current graph.
6992
0
    cgraph->visited_hash_set.keys[node_hash_pos] = node;
6993
0
    ggml_bitset_set(cgraph->visited_hash_set.used, node_hash_pos);
6994
0
    cgraph->use_counts[node_hash_pos] = 0;
6995
6996
0
    for (int i = 0; i < GGML_MAX_SRC; ++i) {
6997
0
        const int k =
6998
0
            (cgraph->order == GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT) ? i :
6999
0
            (cgraph->order == GGML_CGRAPH_EVAL_ORDER_RIGHT_TO_LEFT) ? (GGML_MAX_SRC-1-i) :
7000
0
            /* unknown order, just fall back to using i */ i;
7001
7002
0
        struct ggml_tensor * src = node->src[k];
7003
0
        if (src) {
7004
0
            const size_t src_hash_pos = ggml_visit_parents_graph(cgraph, src, compute);
7005
7006
            // Update the use count for this operand.
7007
0
            cgraph->use_counts[src_hash_pos]++;
7008
0
        }
7009
0
    }
7010
7011
0
    if (node->op == GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_PARAM)) {
7012
        // reached a leaf node, not part of the gradient graph (e.g. a constant)
7013
0
        GGML_ASSERT(cgraph->n_leafs < cgraph->size);
7014
7015
0
        if (strlen(node->name) == 0) {
7016
0
            ggml_format_name(node, "leaf_%d", cgraph->n_leafs);
7017
0
        }
7018
7019
0
        cgraph->leafs[cgraph->n_leafs] = node;
7020
0
        cgraph->n_leafs++;
7021
0
    } else {
7022
0
        GGML_ASSERT(cgraph->n_nodes < cgraph->size);
7023
7024
0
        if (strlen(node->name) == 0) {
7025
0
            ggml_format_name(node, "node_%d", cgraph->n_nodes);
7026
0
        }
7027
7028
0
        cgraph->nodes[cgraph->n_nodes] = node;
7029
0
        cgraph->n_nodes++;
7030
0
    }
7031
7032
0
    return node_hash_pos;
7033
0
}
7034
7035
0
static void ggml_build_forward_impl(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor, bool expand, bool compute) {
7036
0
    if (!expand) {
7037
        // TODO: this branch isn't accessible anymore, maybe move this to ggml_build_forward_expand
7038
0
        ggml_graph_clear(cgraph);
7039
0
    }
7040
7041
0
    const int n_old = cgraph->n_nodes;
7042
7043
0
    ggml_visit_parents_graph(cgraph, tensor, compute);
7044
7045
0
    const int n_new = cgraph->n_nodes - n_old;
7046
0
    GGML_PRINT_DEBUG("%s: visited %d new nodes\n", __func__, n_new);
7047
7048
0
    if (n_new > 0) {
7049
        // the last added node should always be starting point
7050
0
        GGML_ASSERT(cgraph->nodes[cgraph->n_nodes - 1] == tensor);
7051
0
    }
7052
0
}
7053
7054
struct ggml_tensor * ggml_build_forward_select(
7055
        struct ggml_cgraph  * cgraph,
7056
        struct ggml_tensor ** tensors,
7057
        int                   n_tensors,
7058
0
        int                   idx) {
7059
0
    GGML_ASSERT(idx >= 0 && idx < n_tensors);
7060
7061
0
    for (int i = 0; i < n_tensors; i++) {
7062
0
        ggml_build_forward_impl(cgraph, tensors[i], true, i == idx ? true : false);
7063
0
    }
7064
7065
0
    return tensors[idx];
7066
0
}
7067
7068
0
void ggml_build_forward_expand(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
7069
0
    ggml_build_forward_impl(cgraph, tensor, true, true);
7070
0
}
7071
7072
void ggml_build_backward_expand(
7073
        struct ggml_context *  ctx,
7074
        struct ggml_cgraph  *  cgraph,
7075
0
        struct ggml_tensor  ** grad_accs) {
7076
0
    GGML_ASSERT(cgraph->n_nodes > 0);
7077
0
    GGML_ASSERT(cgraph->grads);
7078
0
    GGML_ASSERT(cgraph->grad_accs);
7079
7080
0
    const int n_nodes_f = cgraph->n_nodes;
7081
7082
0
    memset(cgraph->grads,     0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
7083
0
    memset(cgraph->grad_accs, 0, cgraph->visited_hash_set.size*sizeof(struct ggml_tensor *));
7084
0
    bool * grads_needed = calloc(cgraph->visited_hash_set.size, sizeof(bool));
7085
7086
0
    {
7087
0
        bool any_params = false;
7088
0
        bool any_loss   = false;
7089
0
        for (int i = 0; i < n_nodes_f; ++i) {
7090
0
            struct ggml_tensor * node = cgraph->nodes[i];
7091
0
            any_params = any_params || (node->flags & GGML_TENSOR_FLAG_PARAM);
7092
0
            any_loss   = any_loss   || (node->flags & GGML_TENSOR_FLAG_LOSS);
7093
0
        }
7094
0
        GGML_ASSERT(any_params && "no trainable parameters found, did you forget to call ggml_set_param?");
7095
0
        GGML_ASSERT(any_loss && "no training loss found, did you forget to call ggml_set_loss?");
7096
0
    }
7097
7098
0
    for (int i = 0; i < n_nodes_f; ++i) {
7099
0
        struct ggml_tensor * node = cgraph->nodes[i];
7100
7101
0
        if (node->type == GGML_TYPE_I32) {
7102
0
            continue;
7103
0
        }
7104
7105
0
        bool node_needs_grad = (node->flags & GGML_TENSOR_FLAG_PARAM) || (node->flags & GGML_TENSOR_FLAG_LOSS);
7106
0
        bool ignore_src[GGML_MAX_SRC] = {false};
7107
0
        switch (node->op) {
7108
            // gradients in node->src[0] for one reason or another have no effect on output gradients
7109
0
            case GGML_OP_IM2COL:      // only used for its shape
7110
0
            case GGML_OP_IM2COL_BACK: // same as IM2COL
7111
0
                ignore_src[0] = true;
7112
0
                break;
7113
0
            case GGML_OP_UNARY: {
7114
0
                const enum ggml_unary_op uop = ggml_get_unary_op(node);
7115
                // SGN and STEP unary ops are piecewise constant
7116
0
                if (uop == GGML_UNARY_OP_SGN || uop == GGML_UNARY_OP_STEP) {
7117
0
                    ignore_src[0] = true;
7118
0
                }
7119
0
            } break;
7120
7121
            // gradients in node->src[1] for one reason or another have no effect on output gradients
7122
0
            case GGML_OP_CPY:           // gradients in CPY target are irrelevant
7123
0
            case GGML_OP_GET_ROWS:      // row indices not differentiable
7124
0
            case GGML_OP_GET_ROWS_BACK: // same as for GET_ROWS
7125
0
            case GGML_OP_ROPE:          // positions not differentiable
7126
0
                ignore_src[1] = true;
7127
0
                break;
7128
7129
0
            default:
7130
0
                break;
7131
0
        }
7132
0
        for (int j = 0; j < GGML_MAX_SRC; ++j) {
7133
0
            if (!node->src[j] || ignore_src[j] || !grads_needed[ggml_hash_find(&cgraph->visited_hash_set, node->src[j])]) {
7134
0
                continue;
7135
0
            }
7136
0
            GGML_ASSERT(node->src[j]->type == GGML_TYPE_F32 || node->src[j]->type == GGML_TYPE_F16);
7137
0
            node_needs_grad = true;
7138
0
            break;
7139
0
        }
7140
0
        if (!node_needs_grad) {
7141
0
            continue;
7142
0
        }
7143
7144
        // inplace operations are currently not supported
7145
0
        GGML_ASSERT(!node->view_src || node->op == GGML_OP_CPY || node->op == GGML_OP_VIEW ||
7146
0
            node->op == GGML_OP_RESHAPE || node->op == GGML_OP_PERMUTE || node->op == GGML_OP_TRANSPOSE);
7147
7148
0
        const size_t ihash = ggml_hash_find(&cgraph->visited_hash_set, node);
7149
0
        GGML_ASSERT(ihash != GGML_HASHSET_FULL);
7150
0
        GGML_ASSERT(ggml_bitset_get(cgraph->visited_hash_set.used, ihash));
7151
0
        if (grad_accs && grad_accs[i]) {
7152
0
            cgraph->grad_accs[ihash] = grad_accs[i];
7153
0
            cgraph->grads[ihash]     = cgraph->grad_accs[ihash];
7154
0
        } else if (node->flags & GGML_TENSOR_FLAG_LOSS) {
7155
            // loss tensors always need a gradient accumulator
7156
0
            cgraph->grad_accs[ihash] = ggml_new_tensor(ctx, GGML_TYPE_F32, GGML_MAX_DIMS, node->ne);
7157
0
            cgraph->grads[ihash]     = cgraph->grad_accs[ihash];
7158
0
        }
7159
0
        grads_needed[ihash] = true;
7160
0
    }
7161
7162
0
    for (int i = n_nodes_f - 1; i >= 0; --i) {
7163
        // inplace operations to add gradients are not created by ggml_compute_backward except for gradient accumulation
7164
        // use allocator to automatically make inplace operations
7165
0
        ggml_compute_backward(ctx, cgraph, i, grads_needed);
7166
0
    }
7167
7168
0
    free(grads_needed);
7169
0
}
7170
7171
0
static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
7172
0
    void * ptr = *p;
7173
0
    ptr = (void *) GGML_PAD((uintptr_t) ptr, align);
7174
0
    *p = (void *) ((char *) ptr + size);
7175
0
    return ptr;
7176
0
}
7177
7178
0
static size_t ggml_graph_nbytes(size_t size, bool grads) {
7179
0
    size_t hash_size = ggml_hash_size(size * 2);
7180
0
    void * p = 0;
7181
0
    incr_ptr_aligned(&p, sizeof(struct ggml_cgraph), 1);
7182
0
    incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // nodes
7183
0
    incr_ptr_aligned(&p, size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // leafs
7184
0
    incr_ptr_aligned(&p, hash_size * sizeof(int32_t), sizeof(int32_t)); // use_counts
7185
0
    incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // hash keys
7186
0
    if (grads) {
7187
0
        incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grads
7188
0
        incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)); // grad_accs
7189
0
    }
7190
0
    incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
7191
7192
0
    size_t nbytes = (size_t) p;
7193
0
    return nbytes;
7194
0
}
7195
7196
0
size_t ggml_graph_overhead_custom(size_t size, bool grads) {
7197
0
    return GGML_OBJECT_SIZE + GGML_PAD(ggml_graph_nbytes(size, grads), GGML_MEM_ALIGN);
7198
0
}
7199
7200
0
size_t ggml_graph_overhead(void) {
7201
0
    return ggml_graph_overhead_custom(GGML_DEFAULT_GRAPH_SIZE, false);
7202
0
}
7203
7204
0
struct ggml_cgraph * ggml_new_graph_custom(struct ggml_context * ctx, size_t size, bool grads) {
7205
0
    const size_t obj_size = ggml_graph_nbytes(size, grads);
7206
0
    struct ggml_object * obj = ggml_new_object(ctx, GGML_OBJECT_TYPE_GRAPH, obj_size);
7207
0
    struct ggml_cgraph * cgraph = (struct ggml_cgraph *) ((char *) ctx->mem_buffer + obj->offs);
7208
7209
    // the size of the hash table is doubled since it needs to hold both nodes and leafs
7210
0
    size_t hash_size = ggml_hash_size(size * 2);
7211
7212
0
    void * p = cgraph + 1;
7213
7214
0
    struct ggml_tensor ** nodes_ptr      =         incr_ptr_aligned(&p, size      * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
7215
0
    struct ggml_tensor ** leafs_ptr      =         incr_ptr_aligned(&p, size      * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
7216
0
    int32_t             * use_counts_ptr =         incr_ptr_aligned(&p, hash_size * sizeof(int32_t), sizeof(int32_t));
7217
0
    struct ggml_tensor ** hash_keys_ptr  =         incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *));
7218
0
    struct ggml_tensor ** grads_ptr      = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
7219
0
    struct ggml_tensor ** grad_accs_ptr  = grads ? incr_ptr_aligned(&p, hash_size * sizeof(struct ggml_tensor *), sizeof(struct ggml_tensor *)) : NULL;
7220
7221
0
    ggml_bitset_t * hash_used = incr_ptr_aligned(&p, ggml_bitset_size(hash_size) * sizeof(ggml_bitset_t), sizeof(ggml_bitset_t));
7222
7223
    // check that we allocated the correct amount of memory
7224
0
    assert(obj_size == (size_t)((char *)p - (char *)cgraph));
7225
7226
0
    *cgraph = (struct ggml_cgraph) {
7227
0
        /*.size         =*/ size,
7228
0
        /*.n_nodes      =*/ 0,
7229
0
        /*.n_leafs      =*/ 0,
7230
0
        /*.nodes        =*/ nodes_ptr,
7231
0
        /*.grads        =*/ grads_ptr,
7232
0
        /*.grad_accs    =*/ grad_accs_ptr,
7233
0
        /*.leafs        =*/ leafs_ptr,
7234
0
        /*.use_counts   =*/ use_counts_ptr,
7235
0
        /*.hash_table   =*/ { hash_size, hash_used, hash_keys_ptr },
7236
0
        /*.order        =*/ GGML_CGRAPH_EVAL_ORDER_LEFT_TO_RIGHT,
7237
0
        /*.uid          =*/ 0,
7238
0
    };
7239
7240
0
    ggml_hash_set_reset(&cgraph->visited_hash_set);
7241
0
    if (grads) {
7242
0
        memset(cgraph->grads,     0, hash_size*sizeof(struct ggml_tensor *));
7243
0
        memset(cgraph->grad_accs, 0, hash_size*sizeof(struct ggml_tensor *));
7244
0
    }
7245
7246
0
    return cgraph;
7247
0
}
7248
7249
0
struct ggml_cgraph * ggml_new_graph(struct ggml_context * ctx) {
7250
0
    return ggml_new_graph_custom(ctx, GGML_DEFAULT_GRAPH_SIZE, false);
7251
0
}
7252
7253
0
struct ggml_cgraph ggml_graph_view(struct ggml_cgraph * cgraph0, int i0, int i1) {
7254
0
    struct ggml_cgraph cgraph = {
7255
0
        /*.size             =*/ 0,
7256
0
        /*.n_nodes          =*/ i1 - i0,
7257
0
        /*.n_leafs          =*/ 0,
7258
0
        /*.nodes            =*/ cgraph0->nodes + i0,
7259
0
        /*.grads            =*/ NULL, // gradients would need visited_hash_set
7260
0
        /*.grad_accs        =*/ NULL,
7261
0
        /*.leafs            =*/ NULL,
7262
0
        /*.use_counts       =*/ cgraph0->use_counts,
7263
0
        /*.visited_hash_set =*/ cgraph0->visited_hash_set,
7264
0
        /*.order            =*/ cgraph0->order,
7265
0
        /*.uid              =*/ 0
7266
0
    };
7267
7268
0
    return cgraph;
7269
0
}
7270
7271
0
void ggml_graph_cpy(struct ggml_cgraph * src, struct ggml_cgraph * dst) {
7272
0
    GGML_ASSERT(dst->size >= src->n_leafs);
7273
0
    GGML_ASSERT(dst->size >= src->n_nodes);
7274
0
    GGML_ASSERT(dst->visited_hash_set.size >= src->visited_hash_set.size);
7275
7276
0
    dst->n_leafs = src->n_leafs;
7277
0
    dst->n_nodes = src->n_nodes;
7278
0
    dst->order   = src->order;
7279
7280
0
    for (int i = 0; i < src->n_leafs; ++i) {
7281
0
        dst->leafs[i] = src->leafs[i];
7282
0
    }
7283
7284
0
    for (int i = 0; i < src->n_nodes; ++i) {
7285
0
        dst->nodes[i] = src->nodes[i];
7286
0
    }
7287
7288
0
    for (size_t i = 0; i < src->visited_hash_set.size; ++i) {
7289
        // copy all hashset keys (tensors) that are in use
7290
0
        if (ggml_bitset_get(src->visited_hash_set.used, i)) {
7291
0
            size_t new_hash_pos = ggml_hash_insert(&dst->visited_hash_set, src->visited_hash_set.keys[i]);
7292
0
            dst->use_counts[new_hash_pos] = src->use_counts[i];
7293
0
        }
7294
0
    }
7295
7296
0
    if (dst->grads) {
7297
0
        memset(dst->grads,     0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
7298
0
        memset(dst->grad_accs, 0, dst->visited_hash_set.size*sizeof(struct ggml_tensor *));
7299
0
    }
7300
0
    if (src->grads) {
7301
0
        GGML_ASSERT(dst->grads     != NULL);
7302
0
        GGML_ASSERT(dst->grad_accs != NULL);
7303
0
        for (int i = 0; i < src->n_nodes; ++i) {
7304
0
            const size_t igrad_src = ggml_hash_find(&src->visited_hash_set, src->nodes[i]);
7305
0
            const size_t igrad_dst = ggml_hash_find(&dst->visited_hash_set, dst->nodes[i]);
7306
7307
0
            GGML_ASSERT(igrad_src != GGML_HASHSET_FULL);
7308
0
            GGML_ASSERT(ggml_bitset_get(src->visited_hash_set.used, igrad_src));
7309
0
            GGML_ASSERT(igrad_dst != GGML_HASHSET_FULL);
7310
0
            GGML_ASSERT(ggml_bitset_get(dst->visited_hash_set.used, igrad_dst));
7311
7312
0
            dst->grads[igrad_dst]     = src->grads[igrad_src];
7313
0
            dst->grad_accs[igrad_dst] = src->grad_accs[igrad_src];
7314
0
        }
7315
0
    }
7316
0
}
7317
7318
0
struct ggml_cgraph * ggml_graph_dup(struct ggml_context * ctx, struct ggml_cgraph * cgraph, bool force_grads) {
7319
0
    struct ggml_cgraph * result = ggml_new_graph_custom(ctx, cgraph->size, cgraph->grads || force_grads);
7320
0
    ggml_graph_cpy(cgraph, result);
7321
0
    return result;
7322
0
}
7323
7324
0
struct ggml_tensor * ggml_set_zero(struct ggml_tensor * tensor) {
7325
0
    if (ggml_is_empty(tensor)) {
7326
0
        return tensor;
7327
0
    }
7328
0
    if (tensor->buffer) {
7329
0
        ggml_backend_tensor_memset(tensor, 0, 0, ggml_nbytes(tensor));
7330
0
    } else {
7331
0
        GGML_ASSERT(tensor->data);
7332
0
        memset(tensor->data, 0, ggml_nbytes(tensor));
7333
0
    }
7334
0
    return tensor;
7335
0
}
7336
7337
0
void ggml_graph_reset(struct ggml_cgraph * cgraph) {
7338
0
    if (!cgraph) {
7339
0
        return;
7340
0
    }
7341
0
    GGML_ASSERT(cgraph->grads != NULL);
7342
7343
0
    for (int i = 0; i < cgraph->n_nodes; i++) {
7344
0
        struct ggml_tensor * node     = cgraph->nodes[i];
7345
0
        struct ggml_tensor * grad_acc = ggml_graph_get_grad_acc(cgraph, node);
7346
7347
0
        if (node->op == GGML_OP_OPT_STEP_ADAMW) {
7348
            // clear momenta
7349
0
            ggml_set_zero(node->src[2]);
7350
0
            ggml_set_zero(node->src[3]);
7351
0
        }
7352
7353
        // initial gradients of loss should be 1, 0 otherwise
7354
0
        if (grad_acc) {
7355
0
            if (node->flags & GGML_TENSOR_FLAG_LOSS) {
7356
0
                GGML_ASSERT(grad_acc->type == GGML_TYPE_F32);
7357
0
                GGML_ASSERT(ggml_is_scalar(grad_acc));
7358
7359
0
                const float onef = 1.0f;
7360
0
                if (grad_acc->buffer) {
7361
0
                    ggml_backend_tensor_set(grad_acc, &onef, 0, sizeof(float));
7362
0
                } else {
7363
0
                    GGML_ASSERT(grad_acc->data);
7364
0
                    *((float *) grad_acc->data) = onef;
7365
0
                }
7366
0
            } else {
7367
0
                ggml_set_zero(grad_acc);
7368
0
            }
7369
0
        }
7370
0
    }
7371
0
}
7372
7373
0
void ggml_graph_clear(struct ggml_cgraph * cgraph) {
7374
0
    cgraph->n_leafs = 0;
7375
0
    cgraph->n_nodes = 0;
7376
0
    ggml_hash_set_reset(&cgraph->visited_hash_set);
7377
0
}
7378
7379
0
int ggml_graph_size(struct ggml_cgraph * cgraph) {
7380
0
    return cgraph->size;
7381
0
}
7382
7383
0
struct ggml_tensor * ggml_graph_node(struct ggml_cgraph * cgraph, int i) {
7384
0
    if (i < 0) {
7385
0
        GGML_ASSERT(cgraph->n_nodes + i >= 0);
7386
0
        return cgraph->nodes[cgraph->n_nodes + i];
7387
0
    }
7388
7389
0
    GGML_ASSERT(i < cgraph->n_nodes);
7390
0
    return cgraph->nodes[i];
7391
0
}
7392
7393
0
struct ggml_tensor ** ggml_graph_nodes(struct ggml_cgraph * cgraph) {
7394
0
    return cgraph->nodes;
7395
0
}
7396
7397
0
int ggml_graph_n_nodes(struct ggml_cgraph * cgraph) {
7398
0
    return cgraph->n_nodes;
7399
0
}
7400
7401
0
void ggml_graph_add_node(struct ggml_cgraph * cgraph, struct ggml_tensor * tensor) {
7402
0
    GGML_ASSERT(cgraph->size > cgraph->n_nodes);
7403
0
    cgraph->nodes[cgraph->n_nodes] = tensor;
7404
0
    cgraph->n_nodes++;
7405
0
}
7406
7407
0
struct ggml_tensor * ggml_graph_get_tensor(const struct ggml_cgraph * cgraph, const char * name) {
7408
0
    for (int i = 0; i < cgraph->n_leafs; i++) {
7409
0
        struct ggml_tensor * leaf = cgraph->leafs[i];
7410
7411
0
        if (strcmp(leaf->name, name) == 0) {
7412
0
            return leaf;
7413
0
        }
7414
0
    }
7415
7416
0
    for (int i = 0; i < cgraph->n_nodes; i++) {
7417
0
        struct ggml_tensor * node = cgraph->nodes[i];
7418
7419
0
        if (strcmp(node->name, name) == 0) {
7420
0
            return node;
7421
0
        }
7422
0
    }
7423
7424
0
    return NULL;
7425
0
}
7426
7427
0
struct ggml_tensor * ggml_graph_get_grad(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
7428
0
    const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
7429
0
    return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grads ? cgraph->grads[igrad] : NULL;
7430
0
}
7431
7432
0
struct ggml_tensor * ggml_graph_get_grad_acc(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
7433
0
    const size_t igrad = ggml_hash_find(&cgraph->visited_hash_set, node);
7434
0
    return igrad != GGML_HASHSET_FULL && ggml_bitset_get(cgraph->visited_hash_set.used, igrad) && cgraph->grad_accs ? cgraph->grad_accs[igrad] : NULL;
7435
0
}
7436
7437
0
void ggml_graph_print(const struct ggml_cgraph * cgraph) {
7438
0
    GGML_LOG_INFO("=== GRAPH ===\n");
7439
7440
0
    GGML_LOG_INFO("n_nodes = %d\n", cgraph->n_nodes);
7441
0
    for (int i = 0; i < cgraph->n_nodes; i++) {
7442
0
        struct ggml_tensor * node = cgraph->nodes[i];
7443
7444
0
        GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 ", %5" PRId64 "] %16s %s\n",
7445
0
                i,
7446
0
                node->ne[0], node->ne[1], node->ne[2],
7447
0
                ggml_op_name(node->op), (node->flags & GGML_TENSOR_FLAG_PARAM) ? "x" :
7448
0
                      ggml_graph_get_grad(cgraph, node) ? "g" : " ");
7449
0
    }
7450
7451
0
    GGML_LOG_INFO("n_leafs = %d\n", cgraph->n_leafs);
7452
0
    for (int i = 0; i < cgraph->n_leafs; i++) {
7453
0
        struct ggml_tensor * node = cgraph->leafs[i];
7454
7455
0
        GGML_LOG_INFO(" - %3d: [ %5" PRId64 ", %5" PRId64 "] %8s %16s\n",
7456
0
                i,
7457
0
                node->ne[0], node->ne[1],
7458
0
                ggml_op_name(node->op),
7459
0
                ggml_get_name(node));
7460
0
    }
7461
7462
0
    GGML_LOG_INFO("========================================\n");
7463
0
}
7464
7465
static int ggml_node_list_find_tensor(const struct ggml_cgraph * cgraph,
7466
                                      const int *                idxs,
7467
                                      int                        count,
7468
0
                                      const struct ggml_tensor * tensor) {
7469
0
    GGML_ASSERT(cgraph && idxs);
7470
0
    for (int i = 0; i < count; ++i) {
7471
0
        const int node_idx = idxs[i];
7472
7473
0
        if (node_idx >= cgraph->n_nodes) {
7474
0
            return -1;
7475
0
        }
7476
0
        if (cgraph->nodes[node_idx] == tensor) {
7477
0
            return i;
7478
0
        }
7479
0
    }
7480
0
    return -1;
7481
0
}
7482
7483
0
static bool ggml_is_constant(const struct ggml_tensor * tensor) {
7484
0
    return tensor->buffer != NULL && ggml_backend_buffer_get_usage(tensor->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && (tensor->flags & GGML_TENSOR_FLAG_PARAM) == 0;
7485
0
}
7486
7487
bool ggml_can_fuse_subgraph_ext(const struct ggml_cgraph * cgraph,
7488
                                const int *                node_idxs,
7489
                                int                        count,
7490
                                const enum ggml_op *       ops,
7491
                                const int *                outputs,
7492
0
                                int                        num_outputs) {
7493
0
    GGML_ASSERT(outputs && num_outputs > 0);
7494
7495
0
    for (int i = 0; i < count; ++i) {
7496
0
        if (node_idxs[i] >= cgraph->n_nodes) {
7497
0
            return false;
7498
0
        }
7499
7500
0
        const struct ggml_tensor * node = cgraph->nodes[node_idxs[i]];
7501
7502
0
        if (node->op != ops[i]) {
7503
0
            return false;
7504
0
        }
7505
7506
0
        if ((node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
7507
0
            return false;
7508
0
        }
7509
7510
0
        if (ggml_node_list_find_tensor(cgraph, outputs, num_outputs, node) != -1) {
7511
0
            continue;
7512
0
        }
7513
7514
0
        if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
7515
0
            return false;
7516
0
        }
7517
7518
0
        int subgraph_uses = 0;
7519
0
        for (int j = i + 1; j < count; ++j) {
7520
0
            const struct ggml_tensor * other_node = cgraph->nodes[node_idxs[j]];
7521
0
            for (int src_idx = 0; src_idx < GGML_MAX_SRC; src_idx++) {
7522
0
                if (other_node->src[src_idx] == node) {
7523
0
                    subgraph_uses++;
7524
0
                }
7525
0
            }
7526
0
        }
7527
7528
0
        if (subgraph_uses != ggml_node_get_use_count(cgraph, node_idxs[i])) {
7529
0
            return false;
7530
0
        }
7531
7532
        // if node is a view, check if the view_src and all its parent view_srcs are within the subgraph.
7533
        // external view sources are allowed only for weight tensors, which are constant for this graph execution.
7534
0
        struct ggml_tensor * view_src = node->view_src;
7535
0
        while (view_src) {
7536
0
            if (ggml_node_list_find_tensor(cgraph, node_idxs, count, view_src) == -1 && !ggml_is_constant(view_src)) {
7537
0
                return false;
7538
0
            }
7539
0
            view_src = view_src->view_src;
7540
0
        }
7541
0
    }
7542
7543
0
    return true;
7544
0
}
7545
7546
// check if node is part of the graph
7547
0
static bool ggml_graph_find(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
7548
0
    if (cgraph == NULL) {
7549
0
        return true;
7550
0
    }
7551
7552
0
    for (int i = 0; i < cgraph->n_nodes; i++) {
7553
0
        if (cgraph->nodes[i] == node) {
7554
0
            return true;
7555
0
        }
7556
0
    }
7557
7558
0
    return false;
7559
0
}
7560
7561
0
static struct ggml_tensor * ggml_graph_get_parent(const struct ggml_cgraph * cgraph, const struct ggml_tensor * node) {
7562
0
    for (int i = 0; i < cgraph->n_nodes; i++) {
7563
0
        struct ggml_tensor * parent = cgraph->nodes[i];
7564
0
        struct ggml_tensor * grad = ggml_graph_get_grad(cgraph, parent);
7565
7566
0
        if (grad == node) {
7567
0
            return parent;
7568
0
        }
7569
0
    }
7570
7571
0
    return NULL;
7572
0
}
7573
7574
0
static void ggml_graph_dump_dot_node_edge(FILE * fp, const struct ggml_cgraph * gb, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label)  {
7575
0
    struct ggml_tensor * gparent = ggml_graph_get_parent(gb, node);
7576
0
    struct ggml_tensor * gparent0 = ggml_graph_get_parent(gb, parent);
7577
0
    fprintf(fp, "  \"%p\" -> \"%p\" [ arrowhead = %s; style = %s; label = \"%s\"; ]\n",
7578
0
            gparent0 ? (void *) gparent0 : (void *) parent,
7579
0
            gparent ? (void *) gparent : (void *) node,
7580
0
            gparent ? "empty" : "vee",
7581
0
            gparent ? "dashed" : "solid",
7582
0
            label);
7583
0
}
7584
7585
0
static void ggml_graph_dump_dot_leaf_edge(FILE * fp, struct ggml_tensor * node, struct ggml_tensor * parent, const char * label)  {
7586
0
    fprintf(fp, "  \"%p\" -> \"%p\" [ label = \"%s\"; ]\n",
7587
0
            (void *) parent,
7588
0
            (void *) node,
7589
0
            label);
7590
0
}
7591
7592
0
void ggml_graph_dump_dot(const struct ggml_cgraph * gb, const struct ggml_cgraph * cgraph, const char * filename) {
7593
0
    char color[16];
7594
7595
0
    FILE * fp = ggml_fopen(filename, "w");
7596
0
    GGML_ASSERT(fp);
7597
7598
0
    fprintf(fp, "digraph G {\n");
7599
0
    fprintf(fp, "  newrank = true;\n");
7600
0
    fprintf(fp, "  rankdir = TB;\n");
7601
7602
0
    for (int i = 0; i < gb->n_nodes; i++) {
7603
0
        struct ggml_tensor * node = gb->nodes[i];
7604
0
        struct ggml_tensor * grad = ggml_graph_get_grad(gb, node);
7605
7606
0
        if (ggml_graph_get_parent(gb, node) != NULL) {
7607
0
            continue;
7608
0
        }
7609
7610
0
        if (node->flags & GGML_TENSOR_FLAG_PARAM) {
7611
0
            snprintf(color, sizeof(color), "yellow");
7612
0
        } else if (grad) {
7613
0
            if (ggml_graph_find(cgraph, node)) {
7614
0
                snprintf(color, sizeof(color), "green");
7615
0
            } else {
7616
0
                snprintf(color, sizeof(color), "lightblue");
7617
0
            }
7618
0
        } else {
7619
0
            snprintf(color, sizeof(color), "white");
7620
0
        }
7621
7622
0
        fprintf(fp, "  \"%p\" [ "
7623
0
                    "style = filled; fillcolor = %s; shape = record; "
7624
0
                    "label=\"",
7625
0
                (void *) node, color);
7626
7627
0
        if (strlen(node->name) > 0) {
7628
0
            fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
7629
0
        } else {
7630
0
            fprintf(fp, "(%s)|", ggml_type_name(node->type));
7631
0
        }
7632
7633
0
        if (ggml_is_matrix(node)) {
7634
0
            fprintf(fp, "%d [%" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], ggml_op_symbol(node->op));
7635
0
        } else {
7636
0
            fprintf(fp, "%d [%" PRId64 ", %" PRId64 ", %" PRId64 "] | <x>%s", i, node->ne[0], node->ne[1], node->ne[2], ggml_op_symbol(node->op));
7637
0
        }
7638
7639
0
        if (grad) {
7640
0
            fprintf(fp, " | <g>%s\"; ]\n", ggml_op_symbol(grad->op));
7641
0
        } else {
7642
0
            fprintf(fp, "\"; ]\n");
7643
0
        }
7644
0
    }
7645
7646
0
    for (int i = 0; i < gb->n_leafs; i++) {
7647
0
        struct ggml_tensor * node = gb->leafs[i];
7648
7649
0
        snprintf(color, sizeof(color), "pink");
7650
7651
0
        fprintf(fp, "  \"%p\" [ "
7652
0
                    "style = filled; fillcolor = %s; shape = record; "
7653
0
                    "label=\"<x>",
7654
0
                (void *) node, color);
7655
7656
0
        if (strlen(node->name) > 0) {
7657
0
            fprintf(fp, "%s (%s)|", node->name, ggml_type_name(node->type));
7658
0
        } else {
7659
0
            fprintf(fp, "(%s)|", ggml_type_name(node->type));
7660
0
        }
7661
7662
0
        fprintf(fp, "CONST %d [%" PRId64 ", %" PRId64 "]", i, node->ne[0], node->ne[1]);
7663
0
        if (ggml_nelements(node) < 5 && node->data != NULL) {
7664
0
            fprintf(fp, " | (");
7665
0
            for (int j = 0; j < ggml_nelements(node); j++) {
7666
                // FIXME: use ggml-backend to obtain the tensor data
7667
                //if (node->type == GGML_TYPE_I8 || node->type == GGML_TYPE_I16 || node->type == GGML_TYPE_I32) {
7668
                //    fprintf(fp, "%d", ggml_get_i32_1d(node, j));
7669
                //}
7670
                //else if (node->type == GGML_TYPE_F32 ||
7671
                //         node->type == GGML_TYPE_F16 ||
7672
                //         node->type == GGML_TYPE_BF16) {
7673
                //    fprintf(fp, "%.1e", (double)ggml_get_f32_1d(node, j));
7674
                //}
7675
                //else
7676
0
                {
7677
0
                    fprintf(fp, "#");
7678
0
                }
7679
0
                if (j < ggml_nelements(node) - 1) {
7680
0
                    fprintf(fp, ", ");
7681
0
                }
7682
0
            }
7683
0
            fprintf(fp, ")");
7684
0
        }
7685
0
        fprintf(fp, "\"; ]\n");
7686
0
    }
7687
7688
0
    for (int i = 0; i < gb->n_nodes; i++) {
7689
0
        struct ggml_tensor * node = gb->nodes[i];
7690
7691
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
7692
0
            if (node->src[j]) {
7693
0
                char label[16];
7694
0
                snprintf(label, sizeof(label), "src %d", j);
7695
0
                ggml_graph_dump_dot_node_edge(fp, gb, node, node->src[j], label);
7696
0
            }
7697
0
        }
7698
0
    }
7699
7700
0
    for (int i = 0; i < gb->n_leafs; i++) {
7701
0
        struct ggml_tensor * node = gb->leafs[i];
7702
7703
0
        for (int j = 0; j < GGML_MAX_SRC; j++) {
7704
0
            if (node->src[j]) {
7705
0
                char label[16];
7706
0
                snprintf(label, sizeof(label), "src %d", j);
7707
0
                ggml_graph_dump_dot_leaf_edge(fp, node, node->src[j], label);
7708
0
            }
7709
0
        }
7710
0
    }
7711
7712
0
    fprintf(fp, "}\n");
7713
7714
0
    fclose(fp);
7715
7716
0
    GGML_LOG_INFO("%s: dot -Tpng %s -o %s.png && open %s.png\n", __func__, filename, filename, filename);
7717
0
}
7718
7719
////////////////////////////////////////////////////////////////////////////////
7720
7721
0
void ggml_set_input(struct ggml_tensor * tensor) {
7722
0
    tensor->flags |= GGML_TENSOR_FLAG_INPUT;
7723
0
}
7724
7725
0
void ggml_set_output(struct ggml_tensor * tensor) {
7726
0
    tensor->flags |= GGML_TENSOR_FLAG_OUTPUT;
7727
0
}
7728
7729
0
void ggml_set_param(struct ggml_tensor * tensor) {
7730
0
    GGML_ASSERT(tensor->op == GGML_OP_NONE);
7731
0
    tensor->flags |= GGML_TENSOR_FLAG_PARAM;
7732
0
}
7733
7734
0
void ggml_set_loss(struct ggml_tensor * tensor) {
7735
0
    GGML_ASSERT(ggml_is_scalar(tensor));
7736
0
    GGML_ASSERT(tensor->type == GGML_TYPE_F32);
7737
0
    tensor->flags |= GGML_TENSOR_FLAG_LOSS;
7738
0
}
7739
7740
////////////////////////////////////////////////////////////////////////////////
7741
7742
0
void ggml_quantize_init(enum ggml_type type) {
7743
0
    ggml_critical_section_start();
7744
7745
0
    switch (type) {
7746
0
        case GGML_TYPE_IQ2_XXS:
7747
0
        case GGML_TYPE_IQ2_XS:
7748
0
        case GGML_TYPE_IQ2_S:
7749
0
        case GGML_TYPE_IQ1_S:
7750
0
        case GGML_TYPE_IQ1_M:   iq2xs_init_impl(type); break;
7751
0
        case GGML_TYPE_IQ3_XXS: iq3xs_init_impl(256); break;
7752
0
        case GGML_TYPE_IQ3_S:   iq3xs_init_impl(512); break;
7753
0
        default: // nothing
7754
0
            break;
7755
0
    }
7756
7757
0
    ggml_critical_section_end();
7758
0
}
7759
7760
0
void ggml_quantize_free(void) {
7761
0
    ggml_critical_section_start();
7762
7763
0
    iq2xs_free_impl(GGML_TYPE_IQ2_XXS);
7764
0
    iq2xs_free_impl(GGML_TYPE_IQ2_XS);
7765
0
    iq2xs_free_impl(GGML_TYPE_IQ2_S);
7766
0
    iq2xs_free_impl(GGML_TYPE_IQ1_S);
7767
0
    iq2xs_free_impl(GGML_TYPE_IQ1_M);
7768
0
    iq3xs_free_impl(256);
7769
0
    iq3xs_free_impl(512);
7770
7771
0
    ggml_critical_section_end();
7772
0
}
7773
7774
0
bool ggml_quantize_requires_imatrix(enum ggml_type type) {
7775
0
    return
7776
0
        type == GGML_TYPE_IQ2_XXS ||
7777
0
        type == GGML_TYPE_IQ2_XS  ||
7778
0
        type == GGML_TYPE_IQ1_S;//   ||
7779
        //type == GGML_TYPE_IQ1_M;
7780
0
}
7781
7782
size_t ggml_quantize_chunk(
7783
        enum ggml_type   type,
7784
           const float * src,
7785
                  void * dst,
7786
               int64_t   start,
7787
               int64_t   nrows,
7788
               int64_t   n_per_row,
7789
0
           const float * imatrix) {
7790
0
    const int64_t n = nrows * n_per_row;
7791
7792
0
    if (ggml_quantize_requires_imatrix(type)) {
7793
0
        GGML_ASSERT(imatrix != NULL);
7794
0
    }
7795
7796
0
    GGML_ASSERT(start % type_traits[type].blck_size == 0);
7797
0
    GGML_ASSERT(start % n_per_row == 0);
7798
7799
0
    ggml_quantize_init(type); // this is noop if already initialized
7800
7801
0
    const size_t start_row = start / n_per_row;
7802
0
    const size_t row_size  = ggml_row_size(type, n_per_row);
7803
7804
0
    size_t result = 0;
7805
7806
0
    switch (type) {
7807
0
        case GGML_TYPE_Q1_0:    result = quantize_q1_0   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7808
0
        case GGML_TYPE_Q2_0:    result = quantize_q2_0   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7809
0
        case GGML_TYPE_Q4_0:    result = quantize_q4_0   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7810
0
        case GGML_TYPE_Q4_1:    result = quantize_q4_1   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7811
0
        case GGML_TYPE_Q5_0:    result = quantize_q5_0   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7812
0
        case GGML_TYPE_Q5_1:    result = quantize_q5_1   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7813
0
        case GGML_TYPE_Q8_0:    result = quantize_q8_0   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7814
0
        case GGML_TYPE_MXFP4:   result = quantize_mxfp4  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7815
0
        case GGML_TYPE_NVFP4:   result = quantize_nvfp4  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7816
0
        case GGML_TYPE_Q2_K:    result = quantize_q2_K   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7817
0
        case GGML_TYPE_Q3_K:    result = quantize_q3_K   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7818
0
        case GGML_TYPE_Q4_K:    result = quantize_q4_K   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7819
0
        case GGML_TYPE_Q5_K:    result = quantize_q5_K   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7820
0
        case GGML_TYPE_Q6_K:    result = quantize_q6_K   (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7821
0
        case GGML_TYPE_TQ1_0:   result = quantize_tq1_0  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7822
0
        case GGML_TYPE_TQ2_0:   result = quantize_tq2_0  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7823
0
        case GGML_TYPE_IQ2_XXS: result = quantize_iq2_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7824
0
        case GGML_TYPE_IQ2_XS:  result = quantize_iq2_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7825
0
        case GGML_TYPE_IQ3_XXS: result = quantize_iq3_xxs(src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7826
0
        case GGML_TYPE_IQ3_S:   result = quantize_iq3_s  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7827
0
        case GGML_TYPE_IQ2_S:   result = quantize_iq2_s  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7828
0
        case GGML_TYPE_IQ1_S:   result = quantize_iq1_s  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7829
0
        case GGML_TYPE_IQ1_M:   result = quantize_iq1_m  (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7830
0
        case GGML_TYPE_IQ4_NL:  result = quantize_iq4_nl (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7831
0
        case GGML_TYPE_IQ4_XS:  result = quantize_iq4_xs (src + start, (char *) dst + start_row * row_size, nrows, n_per_row, imatrix); break;
7832
0
        case GGML_TYPE_F16:
7833
0
            {
7834
0
                size_t elemsize = sizeof(ggml_fp16_t);
7835
0
                ggml_fp32_to_fp16_row(src + start, (ggml_fp16_t *)dst + start, n);
7836
0
                result = n * elemsize;
7837
0
            } break;
7838
0
        case GGML_TYPE_BF16:
7839
0
            {
7840
0
                size_t elemsize = sizeof(ggml_bf16_t);
7841
0
                ggml_fp32_to_bf16_row_ref(src + start, (ggml_bf16_t *)dst + start, n);
7842
0
                result = n * elemsize;
7843
0
            } break;
7844
0
        case GGML_TYPE_F32:
7845
0
            {
7846
0
                size_t elemsize = sizeof(float);
7847
0
                result = n * elemsize;
7848
0
                memcpy((uint8_t *)dst + start * elemsize, src + start, result);
7849
0
            } break;
7850
0
        default:
7851
0
            assert(false);
7852
0
    }
7853
7854
0
    GGML_ASSERT(result == nrows * row_size);
7855
7856
0
    return result;
7857
0
}
7858
7859
////////////////////////////////////////////////////////////////////////////////
7860
7861
0
void ggml_log_get(ggml_log_callback * log_callback, void ** user_data) {
7862
0
    *log_callback = g_logger_state.log_callback;
7863
0
    *user_data    = g_logger_state.log_callback_user_data;
7864
0
}
7865
7866
0
void ggml_log_set(ggml_log_callback log_callback, void * user_data) {
7867
0
    g_logger_state.log_callback = log_callback ? log_callback : ggml_log_callback_default;
7868
0
    g_logger_state.log_callback_user_data = user_data;
7869
0
}
7870
7871
0
void ggml_threadpool_params_init(struct ggml_threadpool_params * p, int n_threads) {
7872
0
    p->n_threads  = n_threads;
7873
0
    p->prio       = 0;     // default priority (usually means normal or inherited)
7874
0
    p->poll       = 50;    // hybrid-polling enabled
7875
0
    p->strict_cpu = false; // no strict placement (all threads share same cpumask)
7876
0
    p->paused     = false; // threads are ready to go
7877
0
    memset(p->cpumask, 0, GGML_MAX_N_THREADS); // all-zero means use the default affinity (usually inherited)
7878
0
}
7879
7880
0
struct ggml_threadpool_params ggml_threadpool_params_default(int n_threads) {
7881
0
    struct ggml_threadpool_params p;
7882
0
    ggml_threadpool_params_init(&p, n_threads);
7883
0
    return p;
7884
0
}
7885
7886
0
bool ggml_threadpool_params_match(const struct ggml_threadpool_params * p0, const struct ggml_threadpool_params * p1) {
7887
0
    if (p0->n_threads  != p1->n_threads  ) return false;
7888
0
    if (p0->prio       != p1->prio       ) return false;
7889
0
    if (p0->poll       != p1->poll       ) return false;
7890
0
    if (p0->strict_cpu != p1->strict_cpu ) return false;
7891
0
    return memcmp(p0->cpumask, p1->cpumask, GGML_MAX_N_THREADS) == 0;
7892
0
}