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