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-backend.cpp # 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-backend.cpp` 2897 lines ยท 112363 bytes Raw Blame History 1 // Note: porting this file to C++ is a work in progress 2 3 #ifdef _WIN32 4 #define WIN32_LEAN_AND_MEAN 5 #ifndef NOMINMAX 6 # define NOMINMAX 7 #endif 8 #include 9 #endif 10 11 #include "ggml-backend.h" 12 #include "ggml-backend-impl.h" 13 #include "ggml-alloc.h" 14 #include "ggml-impl.h" 15 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include 22 #include 23 #include 24 #include 25 26 #ifdef __APPLE__ 27 #include 28 #include 29 #endif 30 31 32 // backend buffer type 33 34 const char * ggml_backend_buft_name(ggml_backend_buffer_type_t buft) { 35 GGML_ASSERT(buft); 36 return buft->iface.get_name(buft); 37 } 38 39 ggml_backend_buffer_t ggml_backend_buft_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 40 GGML_ASSERT(buft); 41 if (size == 0) { 42 // return a dummy buffer for zero-sized allocations 43 return ggml_backend_buffer_init(buft, {}, NULL, 0); 44 } 45 return buft->iface.alloc_buffer(buft, size); 46 } 47 48 // shared planning logic for allocating a list of tensors into one or more buffers of the given type 49 struct ggml_backend_buft_alloc_buffer_n_plan_item { 50 size_t size; // total bytes for this buffer 51 int first; // first tensor index (inclusive) 52 int last; // last tensor index (exclusive) 53 }; 54 55 using ggml_backend_buft_alloc_buffer_n_plan_t = std::vector; 56 57 static ggml_backend_buft_alloc_buffer_n_plan_t ggml_backend_buft_alloc_buffer_n_plan( 58 ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { 59 ggml_backend_buft_alloc_buffer_n_plan_t plan; 60 61 const size_t alignment = ggml_backend_buft_get_alignment(buft); 62 const size_t max_size = ggml_backend_buft_get_max_size(buft); 63 64 size_t cur_buf_size = 0; 65 int first = 0; 66 67 for (int i = 0; i < n_tensors; i++) { 68 size_t this_size = 0; 69 struct ggml_tensor * t = tensors[i]; 70 if (t->data == NULL && t->view_src == NULL) { 71 this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment); 72 } 73 74 // flush the current buffer if adding this tensor would exceed max_size 75 if (cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) { 76 plan.push_back({ cur_buf_size, first, i }); 77 cur_buf_size = this_size; 78 first = i; 79 } else { 80 cur_buf_size += this_size; 81 } 82 } 83 84 if (cur_buf_size > 0) { 85 plan.push_back({ cur_buf_size, first, n_tensors }); 86 } 87 88 return plan; 89 } 90 91 // default implementation of alloc_buffer_n 92 // allocates tensors from a list into one or more buffers of the given type 93 static ggml_backend_buffer_t ggml_backend_buft_alloc_buffer_n_default(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { 94 const ggml_backend_buft_alloc_buffer_n_plan_t plan = ggml_backend_buft_alloc_buffer_n_plan(buft, tensors, n_tensors); 95 96 std::vector buffers; 97 buffers.reserve(plan.size()); 98 99 for (const ggml_backend_buft_alloc_buffer_n_plan_item & item : plan) { 100 ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, item.size); 101 if (buffer == NULL) { 102 GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), item.size); 103 for (ggml_backend_buffer_t b : buffers) { 104 ggml_backend_buffer_free(b); 105 } 106 return NULL; 107 } 108 109 struct ggml_tallocr tallocr = ggml_tallocr_new(buffer); 110 111 // allocate tensors in the current buffer 112 struct ggml_tensor * t_failed = NULL; 113 for (int j = item.first; j < item.last; j++) { 114 struct ggml_tensor * t = tensors[j]; 115 if (t->data == NULL) { 116 if (t->view_src == NULL) { 117 if (ggml_tallocr_alloc(&tallocr, t) != GGML_STATUS_SUCCESS) { 118 t_failed = t; 119 break; 120 } 121 } else if (t->buffer == NULL) { 122 if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) { 123 t_failed = t; 124 break; 125 } 126 } 127 } else { 128 if (t->view_src != NULL && t->buffer == NULL) { 129 // view of a pre-allocated tensor 130 if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) { 131 t_failed = t; 132 break; 133 } 134 } 135 } 136 } 137 if (t_failed != NULL) { 138 GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t_failed->name); 139 for (ggml_backend_buffer_t b : buffers) { 140 ggml_backend_buffer_free(b); 141 } 142 ggml_backend_buffer_free(buffer); 143 return NULL; 144 } 145 146 buffers.push_back(buffer); 147 } 148 149 if (buffers.empty()) { 150 return NULL; 151 } 152 153 if (buffers.size() == 1) { 154 return buffers[0]; 155 } 156 157 return ggml_backend_multi_buffer_alloc_buffer(buffers.data(), buffers.size()); 158 } 159 160 // default implementation of get_alloc_size_n 161 // returns the total size that alloc_buffer_n_default would allocate for the given tensors 162 static size_t ggml_backend_buft_get_alloc_size_n_default(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { 163 const ggml_backend_buft_alloc_buffer_n_plan_t plan = ggml_backend_buft_alloc_buffer_n_plan(buft, tensors, n_tensors); 164 165 size_t total = 0; 166 for (const ggml_backend_buft_alloc_buffer_n_plan_item & item : plan) { 167 total += item.size; 168 } 169 return total; 170 } 171 172 ggml_backend_buffer_t ggml_backend_buft_alloc_buffer_n(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { 173 GGML_ASSERT(buft); 174 if (buft->iface.alloc_buffer_n) { 175 return buft->iface.alloc_buffer_n(buft, tensors, n_tensors); 176 } 177 return ggml_backend_buft_alloc_buffer_n_default(buft, tensors, n_tensors); 178 } 179 180 size_t ggml_backend_buft_get_alignment(ggml_backend_buffer_type_t buft) { 181 GGML_ASSERT(buft); 182 return buft->iface.get_alignment(buft); 183 } 184 185 size_t ggml_backend_buft_get_max_size(ggml_backend_buffer_type_t buft) { 186 GGML_ASSERT(buft); 187 // get_max_size is optional, defaults to SIZE_MAX 188 if (buft->iface.get_max_size) { 189 return buft->iface.get_max_size(buft); 190 } 191 return SIZE_MAX; 192 } 193 194 size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * tensor) { 195 GGML_ASSERT(buft); 196 // get_alloc_size is optional, defaults to ggml_nbytes 197 if (buft->iface.get_alloc_size) { 198 size_t size = buft->iface.get_alloc_size(buft, tensor); 199 assert(size >= ggml_nbytes(tensor)); 200 201 // [TAG_ALLOC_SIZE_EXPAND] 202 // if you hit this assert, update ggml_backend_op_alloc_size_may_expand() accordingly 203 GGML_ASSERT(size <= ggml_nbytes(tensor) || 204 ggml_op_is_empty(tensor->op) || 205 ggml_is_quantized(tensor->type) || // [TAG_ALLOC_SIZE_EXPAND] 206 ggml_op_alloc_size_may_expand(tensor->op)); 207 208 return size; 209 } 210 return ggml_nbytes(tensor); 211 } 212 213 size_t ggml_backend_buft_get_alloc_size_n(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) { 214 GGML_ASSERT(buft); 215 if (buft->iface.get_alloc_size_n) { 216 return buft->iface.get_alloc_size_n(buft, tensors, n_tensors); 217 } 218 return ggml_backend_buft_get_alloc_size_n_default(buft, tensors, n_tensors); 219 } 220 221 bool ggml_backend_buft_is_host(ggml_backend_buffer_type_t buft) { 222 GGML_ASSERT(buft); 223 if (buft->iface.is_host) { 224 return buft->iface.is_host(buft); 225 } 226 return false; 227 } 228 229 ggml_backend_dev_t ggml_backend_buft_get_device(ggml_backend_buffer_type_t buft) { 230 GGML_ASSERT(buft); 231 return buft->device; 232 } 233 234 // backend buffer 235 236 ggml_backend_buffer_t ggml_backend_buffer_init( 237 ggml_backend_buffer_type_t buft, 238 struct ggml_backend_buffer_i iface, 239 void * context, 240 size_t size) { 241 ggml_backend_buffer_t buffer = new ggml_backend_buffer { 242 /* .interface = */ iface, 243 /* .buft = */ buft, 244 /* .context = */ context, 245 /* .size = */ size, 246 /* .usage = */ GGML_BACKEND_BUFFER_USAGE_ANY 247 }; 248 249 return buffer; 250 } 251 252 const char * ggml_backend_buffer_name(ggml_backend_buffer_t buffer) { 253 return ggml_backend_buft_name(ggml_backend_buffer_get_type(buffer)); 254 } 255 256 void ggml_backend_buffer_free(ggml_backend_buffer_t buffer) { 257 if (buffer == NULL) { 258 return; 259 } 260 261 if (buffer->iface.free_buffer != NULL) { 262 buffer->iface.free_buffer(buffer); 263 } 264 delete buffer; 265 } 266 267 size_t ggml_backend_buffer_get_size(ggml_backend_buffer_t buffer) { 268 GGML_ASSERT(buffer); 269 return buffer->size; 270 } 271 272 void * ggml_backend_buffer_get_base(ggml_backend_buffer_t buffer) { 273 GGML_ASSERT(buffer); 274 // get_base is optional if the buffer is zero-sized 275 if (!ggml_backend_buffer_is_meta(buffer) && buffer->size == 0) { 276 return NULL; 277 } 278 279 // FIXME JG: a multi_buffer has a non-zero size, according to the above comment get_base is not optional, 280 // I don't know whether the above comment is correct 281 if (!buffer->iface.get_base) { 282 return NULL; 283 } 284 285 void * base = buffer->iface.get_base(buffer); 286 287 GGML_ASSERT(base != NULL && "backend buffer base cannot be NULL"); 288 289 return base; 290 } 291 292 enum ggml_status ggml_backend_buffer_init_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) { 293 GGML_ASSERT(buffer); 294 // init_tensor is optional 295 if (buffer->iface.init_tensor) { 296 return buffer->iface.init_tensor(buffer, tensor); 297 } 298 return GGML_STATUS_SUCCESS; 299 } 300 301 void ggml_backend_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { 302 GGML_ASSERT(buffer); 303 // clear is optional if the buffer is zero-sized 304 if (buffer->size == 0) { 305 return; 306 } 307 308 buffer->iface.clear(buffer, value); 309 } 310 311 size_t ggml_backend_buffer_get_alignment(ggml_backend_buffer_t buffer) { 312 return ggml_backend_buft_get_alignment(ggml_backend_buffer_get_type(buffer)); 313 } 314 315 size_t ggml_backend_buffer_get_max_size(ggml_backend_buffer_t buffer) { 316 return ggml_backend_buft_get_max_size(ggml_backend_buffer_get_type(buffer)); 317 } 318 319 size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor) { 320 return ggml_backend_buft_get_alloc_size(ggml_backend_buffer_get_type(buffer), tensor); 321 } 322 323 bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) { 324 return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer)); 325 } 326 327 void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) { 328 GGML_ASSERT(buffer); 329 buffer->usage = usage; 330 331 // FIXME: add a generic callback to the buffer interface 332 if (ggml_backend_buffer_is_multi_buffer(buffer)) { 333 ggml_backend_multi_buffer_set_usage(buffer, usage); 334 } else if (ggml_backend_buffer_is_meta(buffer)) { 335 ggml_backend_meta_buffer_set_usage(buffer, usage); 336 } 337 } 338 339 enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage(ggml_backend_buffer_t buffer) { 340 GGML_ASSERT(buffer); 341 return buffer->usage; 342 } 343 344 ggml_backend_buffer_type_t ggml_backend_buffer_get_type(ggml_backend_buffer_t buffer) { 345 GGML_ASSERT(buffer); 346 return buffer->buft; 347 } 348 349 void ggml_backend_buffer_reset(ggml_backend_buffer_t buffer) { 350 GGML_ASSERT(buffer); 351 if (buffer->iface.reset) { 352 buffer->iface.reset(buffer); 353 } 354 } 355 356 bool ggml_backend_buffer_copy_tensor(const struct ggml_tensor * src, struct ggml_tensor * dst) { 357 ggml_backend_buffer_t dst_buf = dst->view_src ? dst->view_src->buffer : dst->buffer; 358 if (dst_buf->iface.cpy_tensor) { 359 return dst_buf->iface.cpy_tensor(dst_buf, src, dst); 360 } 361 return false; 362 } 363 364 // backend 365 366 ggml_guid_t ggml_backend_guid(ggml_backend_t backend) { 367 if (backend == NULL) { 368 return NULL; 369 } 370 return backend->guid; 371 } 372 373 const char * ggml_backend_name(ggml_backend_t backend) { 374 if (backend == NULL) { 375 return "NULL"; 376 } 377 return backend->iface.get_name(backend); 378 } 379 380 void ggml_backend_free(ggml_backend_t backend) { 381 if (backend == NULL) { 382 return; 383 } 384 385 backend->iface.free(backend); 386 } 387 388 ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend) { 389 GGML_ASSERT(backend); 390 return ggml_backend_dev_buffer_type(backend->device); 391 } 392 393 ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size) { 394 return ggml_backend_buft_alloc_buffer(ggml_backend_get_default_buffer_type(backend), size); 395 } 396 397 size_t ggml_backend_get_alignment(ggml_backend_t backend) { 398 return ggml_backend_buft_get_alignment(ggml_backend_get_default_buffer_type(backend)); 399 } 400 401 size_t ggml_backend_get_max_size(ggml_backend_t backend) { 402 return ggml_backend_buft_get_max_size(ggml_backend_get_default_buffer_type(backend)); 403 } 404 405 template 406 static void ggml_backend_tensor_buft_groups(size_t n_tensors, cb_get_buffer && get_buffer, std::vector> & groups) { 407 std::unordered_map buft_idx; 408 groups.clear(); 409 for (size_t i = 0; i < n_tensors; i++) { 410 ggml_backend_buffer_t buf = get_buffer(i); 411 auto it = buft_idx.find(buf->buft); 412 if (it == buft_idx.end()) { 413 buft_idx[buf->buft] = groups.size(); 414 groups.emplace_back(); 415 } 416 groups[buft_idx[buf->buft]].push_back(i); 417 } 418 } 419 420 static bool ggml_backend_tensor_batch_is_2d( 421 const struct ggml_tensor * const * tensors, 422 const size_t * offsets, 423 const size_t * sizes, 424 const size_t * data_offsets, 425 size_t n_tensors, 426 size_t * base_offset, 427 size_t * size, 428 size_t * stride_tensor, 429 size_t * stride_data) { 430 if (n_tensors <= 1) { 431 return false; 432 } 433 434 const struct ggml_tensor * tensor = tensors[0]; 435 const size_t size0 = sizes[0]; 436 437 if (size0 == 0 || offsets[1] < offsets[0] || data_offsets[1] < data_offsets[0]) { 438 return false; 439 } 440 441 const size_t stride_tensor0 = offsets[1] - offsets[0]; 442 const size_t stride_data0 = data_offsets[1] - data_offsets[0]; 443 444 for (size_t i = 1; i < n_tensors; i++) { 445 if (tensors[i] != tensor || sizes[i] != size0) { 446 return false; 447 } 448 if (offsets[i] != offsets[0] + i*stride_tensor0 || data_offsets[i] != data_offsets[0] + i*stride_data0) { 449 return false; 450 } 451 } 452 453 *base_offset = offsets[0]; 454 *size = size0; 455 *stride_tensor = stride_tensor0; 456 *stride_data = stride_data0; 457 458 return true; 459 } 460 461 void ggml_backend_tensor_set_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 462 GGML_ASSERT(backend); 463 GGML_ASSERT(tensor); 464 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 465 GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); 466 467 if (backend->iface.set_tensor_async == NULL) { 468 ggml_backend_synchronize(backend); 469 ggml_backend_tensor_set(tensor, data, offset, size); 470 } else { 471 backend->iface.set_tensor_async(backend, tensor, data, offset, size); 472 } 473 } 474 475 void ggml_backend_tensor_get_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { 476 GGML_ASSERT(backend); 477 GGML_ASSERT(tensor); 478 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 479 GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds"); 480 481 if (backend->iface.get_tensor_async == NULL) { 482 ggml_backend_synchronize(backend); 483 ggml_backend_tensor_get(tensor, data, offset, size); 484 } else { 485 backend->iface.get_tensor_async(backend, tensor, data, offset, size); 486 } 487 } 488 489 void ggml_backend_tensor_set_2d_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, 490 size_t n_copies, size_t stride_tensor, size_t stride_data) { 491 GGML_ASSERT(backend); 492 GGML_ASSERT(tensor); 493 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 494 495 if (n_copies <= 1 || backend->iface.set_tensor_2d_async == NULL) { 496 for (size_t i = 0; i < n_copies; i++) { 497 ggml_backend_tensor_set_async(backend, tensor, (const char *) data + i*stride_data, offset + i*stride_tensor, size); 498 } 499 return; 500 } 501 if (size == 0) { 502 return; 503 } 504 505 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 506 GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); 507 backend->iface.set_tensor_2d_async(backend, tensor, data, offset, size, n_copies, stride_tensor, stride_data); 508 } 509 510 void ggml_backend_tensor_get_2d_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, 511 size_t n_copies, size_t stride_tensor, size_t stride_data) { 512 GGML_ASSERT(backend); 513 GGML_ASSERT(tensor); 514 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 515 516 if (n_copies <= 1 || backend->iface.get_tensor_2d_async == NULL) { 517 for (size_t i = 0; i < n_copies; i++) { 518 ggml_backend_tensor_get_async(backend, tensor, (char *) data + i*stride_data, offset + i*stride_tensor, size); 519 } 520 return; 521 } 522 if (size == 0) { 523 return; 524 } 525 526 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 527 GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor read out of bounds"); 528 backend->iface.get_tensor_2d_async(backend, tensor, data, offset, size, n_copies, stride_tensor, stride_data); 529 } 530 531 void ggml_backend_tensor_set(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 532 GGML_ASSERT(tensor); 533 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 534 GGML_ASSERT(buf != NULL && "tensor buffer not set"); 535 536 if (size == 0) { 537 return; 538 } 539 540 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 541 GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); 542 543 buf->iface.set_tensor(buf, tensor, data, offset, size); 544 } 545 546 void ggml_backend_tensor_get(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { 547 GGML_ASSERT(tensor); 548 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 549 GGML_ASSERT(buf != NULL && "tensor buffer not set"); 550 551 if (size == 0) { 552 return; 553 } 554 555 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 556 GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds"); 557 558 buf->iface.get_tensor(buf, tensor, data, offset, size); 559 } 560 561 void ggml_backend_tensor_set_2d(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, 562 size_t n_copies, size_t stride_tensor, size_t stride_data) { 563 GGML_ASSERT(tensor); 564 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 565 GGML_ASSERT(buf != NULL && "tensor buffer not set"); 566 567 if (n_copies <= 1 || buf->iface.set_tensor_2d == NULL) { 568 for (size_t i = 0; i < n_copies; i++) { 569 ggml_backend_tensor_set(tensor, (const char *) data + i*stride_data, offset + i*stride_tensor, size); 570 } 571 return; 572 } 573 if (size == 0) { 574 return; 575 } 576 577 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 578 GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); 579 580 buf->iface.set_tensor_2d(buf, tensor, data, offset, size, n_copies, stride_tensor, stride_data); 581 } 582 583 void ggml_backend_tensor_get_2d(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, 584 size_t n_copies, size_t stride_tensor, size_t stride_data) { 585 GGML_ASSERT(tensor); 586 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 587 GGML_ASSERT(buf != NULL && "tensor buffer not set"); 588 589 if (n_copies <= 1 || buf->iface.get_tensor_2d == NULL) { 590 for (size_t i = 0; i < n_copies; i++) { 591 ggml_backend_tensor_get(tensor, (char *) data + i*stride_data, offset + i*stride_tensor, size); 592 } 593 return; 594 } 595 if (size == 0) { 596 return; 597 } 598 599 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 600 GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor read out of bounds"); 601 602 buf->iface.get_tensor_2d(buf, tensor, data, offset, size, n_copies, stride_tensor, stride_data); 603 } 604 605 void ggml_backend_tensor_set_n(struct ggml_tensor * const * tensors, const void * data, 606 const size_t * offsets, const size_t * sizes, const size_t * data_offsets, size_t n_tensors) { 607 if (n_tensors == 0) { 608 return; 609 } 610 611 std::vector data_ptrs(n_tensors); 612 for (size_t i = 0; i < n_tensors; i++) { 613 data_ptrs[i] = (const char *) data + data_offsets[i]; 614 } 615 616 ggml_backend_buffer_t buf = NULL; 617 bool same_buft = true; 618 619 for (size_t i = 0; i < n_tensors; i++) { 620 GGML_ASSERT(tensors[i] != NULL); 621 ggml_backend_buffer_t tensor_buf = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 622 GGML_ASSERT(tensor_buf != NULL && "tensor buffer not set"); 623 GGML_ASSERT(tensors[i]->data != NULL && "tensor not allocated"); 624 GGML_ASSERT(offsets[i] + sizes[i] <= ggml_nbytes(tensors[i]) && "tensor write out of bounds"); 625 626 if (buf == NULL) { 627 buf = tensor_buf; 628 } else if (buf->buft != tensor_buf->buft) { 629 same_buft = false; 630 } 631 } 632 633 if (same_buft && buf->iface.set_tensor_n != NULL) { 634 buf->iface.set_tensor_n(buf, tensors, data_ptrs.data(), offsets, sizes, n_tensors); 635 return; 636 } 637 638 if (!same_buft) { 639 std::vector> groups; 640 ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) { 641 return tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 642 }, groups); 643 644 for (size_t g = 0; g < groups.size(); g++) { 645 std::vector g_tensors; 646 std::vector g_offsets; 647 std::vector g_sizes; 648 std::vector g_data_offsets; 649 g_tensors.reserve(groups[g].size()); 650 g_offsets.reserve(groups[g].size()); 651 g_sizes.reserve(groups[g].size()); 652 g_data_offsets.reserve(groups[g].size()); 653 654 for (size_t i : groups[g]) { 655 g_tensors.push_back(tensors[i]); 656 g_offsets.push_back(offsets[i]); 657 g_sizes.push_back(sizes[i]); 658 g_data_offsets.push_back(data_offsets[i]); 659 } 660 661 ggml_backend_tensor_set_n(g_tensors.data(), data, g_offsets.data(), g_sizes.data(), g_data_offsets.data(), g_tensors.size()); 662 } 663 return; 664 } 665 666 size_t base_offset = 0, size = 0, stride_tensor = 0, stride_data = 0; 667 if (ggml_backend_tensor_batch_is_2d(tensors, offsets, sizes, data_offsets, n_tensors, 668 &base_offset, &size, &stride_tensor, &stride_data)) { 669 ggml_backend_tensor_set_2d(tensors[0], data_ptrs[0], base_offset, size, 670 n_tensors, stride_tensor, stride_data); 671 return; 672 } 673 674 for (size_t i = 0; i < n_tensors; i++) { 675 ggml_backend_tensor_set(tensors[i], data_ptrs[i], offsets[i], sizes[i]); 676 } 677 } 678 679 void ggml_backend_tensor_get_n(const struct ggml_tensor * const * tensors, void * data, 680 const size_t * offsets, const size_t * sizes, const size_t * data_offsets, size_t n_tensors) { 681 if (n_tensors == 0) { 682 return; 683 } 684 685 std::vector data_ptrs(n_tensors); 686 for (size_t i = 0; i < n_tensors; i++) { 687 data_ptrs[i] = (char *) data + data_offsets[i]; 688 } 689 690 ggml_backend_buffer_t buf = NULL; 691 bool same_buft = true; 692 693 for (size_t i = 0; i < n_tensors; i++) { 694 GGML_ASSERT(tensors[i] != NULL); 695 ggml_backend_buffer_t tensor_buf = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 696 GGML_ASSERT(tensor_buf != NULL && "tensor buffer not set"); 697 GGML_ASSERT(tensors[i]->data != NULL && "tensor not allocated"); 698 GGML_ASSERT(offsets[i] + sizes[i] <= ggml_nbytes(tensors[i]) && "tensor read out of bounds"); 699 700 if (buf == NULL) { 701 buf = tensor_buf; 702 } else if (buf->buft != tensor_buf->buft) { 703 same_buft = false; 704 } 705 } 706 707 if (same_buft && buf->iface.get_tensor_n != NULL) { 708 buf->iface.get_tensor_n(buf, tensors, data_ptrs.data(), offsets, sizes, n_tensors); 709 return; 710 } 711 712 if (!same_buft) { 713 std::vector> groups; 714 ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) { 715 return tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer; 716 }, groups); 717 718 for (size_t g = 0; g < groups.size(); g++) { 719 std::vector g_tensors; 720 std::vector g_offsets; 721 std::vector g_sizes; 722 std::vector g_data_offsets; 723 g_tensors.reserve(groups[g].size()); 724 g_offsets.reserve(groups[g].size()); 725 g_sizes.reserve(groups[g].size()); 726 g_data_offsets.reserve(groups[g].size()); 727 728 for (size_t i : groups[g]) { 729 g_tensors.push_back(tensors[i]); 730 g_offsets.push_back(offsets[i]); 731 g_sizes.push_back(sizes[i]); 732 g_data_offsets.push_back(data_offsets[i]); 733 } 734 735 ggml_backend_tensor_get_n(g_tensors.data(), data, g_offsets.data(), g_sizes.data(), g_data_offsets.data(), g_tensors.size()); 736 } 737 return; 738 } 739 740 size_t base_offset = 0, size = 0, stride_tensor = 0, stride_data = 0; 741 if (ggml_backend_tensor_batch_is_2d(tensors, offsets, sizes, data_offsets, n_tensors, 742 &base_offset, &size, &stride_tensor, &stride_data)) { 743 ggml_backend_tensor_get_2d(tensors[0], data_ptrs[0], base_offset, size, 744 n_tensors, stride_tensor, stride_data); 745 return; 746 } 747 748 for (size_t i = 0; i < n_tensors; i++) { 749 ggml_backend_tensor_get(tensors[i], data_ptrs[i], offsets[i], sizes[i]); 750 } 751 } 752 753 void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { 754 GGML_ASSERT(tensor); 755 ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 756 757 if (size == 0) { 758 return; 759 } 760 761 GGML_ASSERT(buf != NULL && "tensor buffer not set"); 762 GGML_ASSERT(tensor->data != NULL && "tensor not allocated"); 763 GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds"); 764 GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer"); 765 766 buf->iface.memset_tensor(buf, tensor, value, offset, size); 767 } 768 769 void ggml_backend_synchronize(ggml_backend_t backend) { 770 GGML_ASSERT(backend); 771 if (backend->iface.synchronize == NULL) { 772 return; 773 } 774 775 backend->iface.synchronize(backend); 776 } 777 778 ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph) { 779 GGML_ASSERT(backend); 780 GGML_ASSERT(backend->iface.graph_plan_create != NULL); 781 782 return backend->iface.graph_plan_create(backend, cgraph); 783 } 784 785 void ggml_backend_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) { 786 GGML_ASSERT(backend); 787 GGML_ASSERT(backend->iface.graph_plan_free != NULL); 788 789 backend->iface.graph_plan_free(backend, plan); 790 } 791 792 enum ggml_status ggml_backend_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) { 793 GGML_ASSERT(backend); 794 GGML_ASSERT(backend->iface.graph_plan_compute != NULL); 795 796 return backend->iface.graph_plan_compute(backend, plan); 797 } 798 799 enum ggml_status ggml_backend_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) { 800 enum ggml_status err = ggml_backend_graph_compute_async(backend, cgraph); 801 ggml_backend_synchronize(backend); 802 return err; 803 } 804 805 enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph) { 806 GGML_ASSERT(backend); 807 return backend->iface.graph_compute(backend, cgraph); 808 } 809 810 bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) { 811 GGML_ASSERT(backend); 812 return ggml_backend_dev_supports_op(backend->device, op); 813 } 814 815 bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) { 816 GGML_ASSERT(backend); 817 return ggml_backend_dev_supports_buft(backend->device, buft); 818 } 819 820 bool ggml_backend_offload_op(ggml_backend_t backend, const struct ggml_tensor * op) { 821 GGML_ASSERT(backend); 822 return ggml_backend_dev_offload_op(backend->device, op); 823 } 824 825 ggml_backend_dev_t ggml_backend_get_device(ggml_backend_t backend) { 826 GGML_ASSERT(backend); 827 return backend->device; 828 } 829 830 // backend copy 831 832 void ggml_backend_tensor_copy(const struct ggml_tensor * src, struct ggml_tensor * dst) { 833 GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts"); 834 835 if (src == dst) { 836 return; 837 } 838 839 if (ggml_backend_buffer_is_host(src->buffer)) { 840 ggml_backend_tensor_set(dst, src->data, 0, ggml_nbytes(src)); 841 } else if (ggml_backend_buffer_is_host(dst->buffer)) { 842 ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src)); 843 } else if (!ggml_backend_buffer_copy_tensor(src, dst)) { 844 #ifndef NDEBUG 845 GGML_LOG_DEBUG("%s: warning: slow copy from %s to %s\n", __func__, ggml_backend_buffer_name(src->buffer), ggml_backend_buffer_name(dst->buffer)); 846 #endif // NDEBUG 847 size_t nbytes = ggml_nbytes(src); 848 void * data = malloc(nbytes); 849 ggml_backend_tensor_get(src, data, 0, nbytes); 850 ggml_backend_tensor_set(dst, data, 0, nbytes); 851 free(data); 852 } 853 } 854 855 void ggml_backend_tensor_copy_n(const struct ggml_tensor * const * srcs, struct ggml_tensor * const * dsts, size_t n_tensors) { 856 if (n_tensors == 0) { 857 return; 858 } 859 860 for (size_t i = 0; i < n_tensors; ++i) { 861 GGML_ASSERT(ggml_are_same_layout(srcs[i], dsts[i]) && "cannot copy tensors with different layouts"); 862 } 863 864 ggml_backend_buffer_t buf = dsts[0]->view_src ? dsts[0]->view_src->buffer : dsts[0]->buffer; 865 bool same_buft = true; 866 for (size_t i = 0; i < n_tensors; ++i) { 867 ggml_backend_buffer_t dst_buf = dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer; 868 if (dst_buf->buft != buf->buft) { 869 same_buft = false; 870 break; 871 } 872 } 873 874 // if cpy_tensor_n returns false, it must not have performed any copies 875 if (same_buft && buf->iface.cpy_tensor_n != NULL) { 876 if (buf->iface.cpy_tensor_n(buf, srcs, dsts, n_tensors)) { 877 return; 878 } 879 } 880 881 if (!same_buft) { 882 std::vector> groups; 883 ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) { 884 return dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer; 885 }, groups); 886 887 for (size_t g = 0; g < groups.size(); g++) { 888 std::vector g_srcs; 889 std::vector g_dsts; 890 g_srcs.reserve(groups[g].size()); 891 g_dsts.reserve(groups[g].size()); 892 893 for (size_t i : groups[g]) { 894 g_srcs.push_back(srcs[i]); 895 g_dsts.push_back(dsts[i]); 896 } 897 898 ggml_backend_tensor_copy_n(g_srcs.data(), g_dsts.data(), g_srcs.size()); 899 } 900 return; 901 } 902 903 for (size_t i = 0; i < n_tensors; ++i) { 904 ggml_backend_tensor_copy(srcs[i], dsts[i]); 905 } 906 } 907 908 void ggml_backend_tensor_copy_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const struct ggml_tensor * src, struct ggml_tensor * dst) { 909 GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts"); 910 911 if (src == dst) { 912 return; 913 } 914 915 GGML_ASSERT(backend_dst); 916 if (backend_dst->iface.cpy_tensor_async != NULL) { 917 if (backend_dst->iface.cpy_tensor_async(backend_src, backend_dst, src, dst)) { 918 return; 919 } 920 } 921 922 // an async copy would normally happen after all the queued operations on both backends are completed 923 // to simulate the same behavior, we need to synchronize both backends first, and do a blocking copy 924 ggml_backend_synchronize(backend_src); 925 ggml_backend_synchronize(backend_dst); 926 ggml_backend_tensor_copy(src, dst); 927 } 928 929 // events 930 931 ggml_backend_event_t ggml_backend_event_new(ggml_backend_dev_t device) { 932 // null device is allowed for the transition period to the device interface 933 if (device == NULL || device->iface.event_new == NULL) { 934 return NULL; 935 } 936 return device->iface.event_new(device); 937 } 938 939 void ggml_backend_event_free(ggml_backend_event_t event) { 940 if (event == NULL) { 941 return; 942 } 943 event->device->iface.event_free(event->device, event); 944 } 945 946 void ggml_backend_event_record(ggml_backend_event_t event, ggml_backend_t backend) { 947 GGML_ASSERT(backend); 948 GGML_ASSERT(backend->iface.event_record != NULL); 949 950 backend->iface.event_record(backend, event); 951 } 952 953 void ggml_backend_event_synchronize(ggml_backend_event_t event) { 954 GGML_ASSERT(event); 955 GGML_ASSERT(event->device->iface.event_synchronize); 956 957 event->device->iface.event_synchronize(event->device, event); 958 } 959 960 void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event) { 961 GGML_ASSERT(backend); 962 GGML_ASSERT(backend->iface.event_wait != NULL); 963 964 backend->iface.event_wait(backend, event); 965 } 966 967 static void ggml_backend_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * cgraph, struct ggml_backend_graph_optimize_params * params) { 968 GGML_ASSERT(backend); 969 if (backend->iface.graph_optimize != NULL) { 970 backend->iface.graph_optimize(backend, cgraph, params); 971 } 972 } 973 974 // Backend device 975 976 const char * ggml_backend_dev_name(ggml_backend_dev_t device) { 977 GGML_ASSERT(device); 978 return device->iface.get_name(device); 979 } 980 981 const char * ggml_backend_dev_description(ggml_backend_dev_t device) { 982 GGML_ASSERT(device); 983 return device->iface.get_description(device); 984 } 985 986 void ggml_backend_dev_memory(ggml_backend_dev_t device, size_t * free, size_t * total) { 987 GGML_ASSERT(device); 988 device->iface.get_memory(device, free, total); 989 } 990 991 enum ggml_backend_dev_type ggml_backend_dev_type(ggml_backend_dev_t device) { 992 GGML_ASSERT(device); 993 return device->iface.get_type(device); 994 } 995 996 void ggml_backend_dev_get_props(ggml_backend_dev_t device, struct ggml_backend_dev_props * props) { 997 GGML_ASSERT(device); 998 memset(props, 0, sizeof(*props)); 999 device->iface.get_props(device, props); 1000 } 1001 1002 ggml_backend_reg_t ggml_backend_dev_backend_reg(ggml_backend_dev_t device) { 1003 GGML_ASSERT(device); 1004 return device->reg; 1005 } 1006 1007 ggml_backend_t ggml_backend_dev_init(ggml_backend_dev_t device, const char * params) { 1008 GGML_ASSERT(device); 1009 return device->iface.init_backend(device, params); 1010 } 1011 1012 ggml_backend_buffer_type_t ggml_backend_dev_buffer_type(ggml_backend_dev_t device) { 1013 GGML_ASSERT(device); 1014 return device->iface.get_buffer_type(device); 1015 } 1016 1017 ggml_backend_buffer_type_t ggml_backend_dev_host_buffer_type(ggml_backend_dev_t device) { 1018 GGML_ASSERT(device); 1019 if (device->iface.get_host_buffer_type == NULL) { 1020 return NULL; 1021 } 1022 1023 return device->iface.get_host_buffer_type(device); 1024 } 1025 1026 ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t device, void * ptr, size_t size, size_t max_tensor_size) { 1027 GGML_ASSERT(device); 1028 return device->iface.buffer_from_host_ptr(device, ptr, size, max_tensor_size); 1029 } 1030 1031 bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op) { 1032 GGML_ASSERT(device); 1033 return device->iface.supports_op(device, op); 1034 } 1035 1036 bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft) { 1037 GGML_ASSERT(device); 1038 return device->iface.supports_buft(device, buft); 1039 } 1040 1041 bool ggml_backend_dev_offload_op(ggml_backend_dev_t device, const struct ggml_tensor * op) { 1042 GGML_ASSERT(device); 1043 if (device->iface.offload_op != NULL) { 1044 return device->iface.offload_op(device, op); 1045 } 1046 1047 return false; 1048 } 1049 1050 // Backend (reg) 1051 1052 const char * ggml_backend_reg_name(ggml_backend_reg_t reg) { 1053 GGML_ASSERT(reg); 1054 return reg->iface.get_name(reg); 1055 } 1056 1057 size_t ggml_backend_reg_dev_count(ggml_backend_reg_t reg) { 1058 GGML_ASSERT(reg); 1059 return reg->iface.get_device_count(reg); 1060 } 1061 1062 ggml_backend_dev_t ggml_backend_reg_dev_get(ggml_backend_reg_t reg, size_t index) { 1063 GGML_ASSERT(reg); 1064 return reg->iface.get_device(reg, index); 1065 } 1066 1067 void * ggml_backend_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) { 1068 GGML_ASSERT(reg); 1069 if (!reg->iface.get_proc_address) { 1070 return NULL; 1071 } 1072 return reg->iface.get_proc_address(reg, name); 1073 } 1074 1075 // multi-buffer buffer 1076 1077 struct ggml_backend_multi_buffer_context { 1078 ggml_backend_buffer_t * buffers; 1079 size_t n_buffers; 1080 }; 1081 1082 static void ggml_backend_multi_buffer_free_buffer(ggml_backend_buffer_t buffer) { 1083 GGML_ASSERT(buffer); 1084 ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context; 1085 for (size_t i = 0; i < ctx->n_buffers; i++) { 1086 ggml_backend_buffer_free(ctx->buffers[i]); 1087 } 1088 1089 free(ctx->buffers); 1090 free(ctx); 1091 } 1092 1093 static void ggml_backend_multi_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { 1094 GGML_ASSERT(buffer); 1095 ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context; 1096 for (size_t i = 0; i < ctx->n_buffers; i++) { 1097 ggml_backend_buffer_clear(ctx->buffers[i], value); 1098 } 1099 } 1100 1101 static const struct ggml_backend_buffer_i ggml_backend_multi_buffer_i = { 1102 /* .free_buffer = */ ggml_backend_multi_buffer_free_buffer, 1103 /* .get_base = */ NULL, 1104 /* .init_tensor = */ NULL, 1105 /* .memset_tensor = */ NULL, 1106 /* .set_tensor = */ NULL, 1107 /* .get_tensor = */ NULL, 1108 /* .set_tensor_2d = */ NULL, 1109 /* .get_tensor_2d = */ NULL, 1110 /* .cpy_tensor = */ NULL, 1111 /* .clear = */ ggml_backend_multi_buffer_clear, 1112 /* .reset = */ NULL, 1113 /* .set_tensor_n = */ NULL, 1114 /* .get_tensor_n = */ NULL, 1115 /* .cpy_tensor_n = */ NULL, 1116 }; 1117 1118 ggml_backend_buffer_t ggml_backend_multi_buffer_alloc_buffer(ggml_backend_buffer_t * buffers, size_t n_buffers) { 1119 ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) malloc(sizeof(struct ggml_backend_multi_buffer_context)); 1120 ctx->n_buffers = n_buffers; 1121 ctx->buffers = (ggml_backend_buffer_t *) malloc(n_buffers * sizeof(ggml_backend_buffer_t)); 1122 1123 GGML_ASSERT(ctx->buffers != NULL); 1124 1125 size_t total_size = 0; 1126 for (size_t i = 0; i < n_buffers; i++) { 1127 ctx->buffers[i] = buffers[i]; 1128 total_size += ggml_backend_buffer_get_size(buffers[i]); 1129 } 1130 1131 return ggml_backend_buffer_init(buffers[0]->buft, ggml_backend_multi_buffer_i, ctx, total_size); 1132 } 1133 1134 bool ggml_backend_buffer_is_multi_buffer(ggml_backend_buffer_t buffer) { 1135 GGML_ASSERT(buffer); 1136 return buffer->iface.free_buffer == ggml_backend_multi_buffer_free_buffer; 1137 } 1138 1139 void ggml_backend_multi_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) { 1140 GGML_ASSERT(buffer); 1141 GGML_ASSERT(ggml_backend_buffer_is_multi_buffer(buffer)); 1142 ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context; 1143 for (size_t i = 0; i < ctx->n_buffers; i++) { 1144 ggml_backend_buffer_set_usage(ctx->buffers[i], usage); 1145 } 1146 } 1147 1148 // creates a copy of the tensor with the same memory layout 1149 static struct ggml_tensor * ggml_dup_tensor_layout(struct ggml_context * ctx, const struct ggml_tensor * tensor) { 1150 struct ggml_tensor * dup = ggml_dup_tensor(ctx, tensor); 1151 for (int i = 0; i < GGML_MAX_DIMS; i++) { 1152 dup->nb[i] = tensor->nb[i]; 1153 } 1154 return dup; 1155 } 1156 1157 static bool ggml_is_view_op(enum ggml_op op) { 1158 return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE; 1159 } 1160 1161 // scheduler 1162 1163 #ifndef GGML_SCHED_MAX_BACKENDS 1164 #define GGML_SCHED_MAX_BACKENDS 16 1165 #endif 1166 1167 #ifndef GGML_SCHED_MAX_SPLIT_INPUTS 1168 #define GGML_SCHED_MAX_SPLIT_INPUTS 30 1169 #endif 1170 1171 #ifndef GGML_SCHED_MAX_COPIES 1172 #define GGML_SCHED_MAX_COPIES 4 1173 #endif 1174 1175 struct ggml_backend_sched_split { 1176 int backend_id; 1177 int i_start; 1178 int i_end; 1179 struct ggml_tensor ** inputs; 1180 int n_inputs; 1181 int inputs_capacity; 1182 // graph view of this split 1183 struct ggml_cgraph graph; 1184 }; 1185 1186 struct ggml_backend_sched { 1187 bool is_reset; // true if the scheduler has been reset since the last graph split 1188 bool is_alloc; 1189 1190 int n_backends; 1191 1192 ggml_backend_t backends[GGML_SCHED_MAX_BACKENDS]; 1193 ggml_backend_buffer_type_t bufts[GGML_SCHED_MAX_BACKENDS]; 1194 ggml_gallocr_t galloc; 1195 1196 // hash map of the nodes in the graph 1197 struct ggml_hash_set hash_set; 1198 int * hv_tensor_backend_ids; // [hash_set.size] 1199 struct ggml_tensor ** hv_tensor_copies; // [hash_set.size][n_backends][n_copies] 1200 1201 int * node_backend_ids; // [graph_size] 1202 int * leaf_backend_ids; // [graph_size] 1203 1204 int * prev_node_backend_ids; // [graph_size] 1205 int * prev_leaf_backend_ids; // [graph_size] 1206 1207 // copy of the graph with modified inputs 1208 struct ggml_cgraph graph; 1209 1210 // graph splits 1211 struct ggml_backend_sched_split * splits; 1212 int n_splits; 1213 int splits_capacity; 1214 1215 // pipeline parallelism support 1216 int n_copies; 1217 int cur_copy; 1218 int next_copy; 1219 ggml_backend_event_t events[GGML_SCHED_MAX_BACKENDS][GGML_SCHED_MAX_COPIES]; 1220 struct ggml_tensor ** graph_inputs; 1221 int n_graph_inputs; 1222 int graph_inputs_capacity; 1223 1224 struct ggml_context * ctx; 1225 1226 ggml_backend_sched_eval_callback callback_eval; 1227 void * callback_eval_user_data; 1228 1229 ggml_backend_sched_copy_callback callback_copy; 1230 void * callback_copy_user_data; 1231 1232 ggml_backend_sched_realloc_callback callback_realloc; 1233 void * callback_realloc_user_data; 1234 1235 char * context_buffer; 1236 size_t context_buffer_size; 1237 1238 bool op_offload; 1239 1240 int debug; 1241 1242 // graph size of the current and the previous scheduling, used by the realloc callback and for debugging 1243 // graph reallocations [GGML_SCHED_DEBUG_REALLOC] 1244 // ref: https://github.com/ggml-org/llama.cpp/pull/17617 1245 int graph_size; 1246 int prev_graph_size; 1247 1248 int debug_realloc; 1249 }; 1250 1251 #define hash_id(tensor) ggml_hash_find_or_insert(&sched->hash_set, tensor) 1252 #define tensor_backend_id(tensor) sched->hv_tensor_backend_ids[hash_id(tensor)] 1253 #define tensor_id_copy(id, backend_id, copy_id) sched->hv_tensor_copies[(id) * sched->n_backends * sched->n_copies + (backend_id) * sched->n_copies + (copy_id)] 1254 #define tensor_copy(tensor, backend_id, copy_id) tensor_id_copy(hash_id(tensor), backend_id, copy_id) 1255 1256 static void ggml_backend_sched_split_inputs_grow(struct ggml_backend_sched_split * split) { 1257 int new_cap = GGML_SCHED_MAX_SPLIT_INPUTS; 1258 if (split->inputs_capacity > 0) { 1259 new_cap = 2*split->inputs_capacity; 1260 GGML_LOG_DEBUG("%s: increasing split inputs capacity from %d to %d\n", __func__, split->inputs_capacity, new_cap); 1261 } 1262 auto * pnew = (struct ggml_tensor **) realloc((void *) split->inputs, new_cap * sizeof(struct ggml_tensor *)); 1263 if (pnew == NULL) { 1264 GGML_LOG_ERROR("%s: failed to allocate %zu bytes\n", __func__, new_cap * sizeof(struct ggml_tensor *)); 1265 GGML_ABORT("failed to grow split inputs container"); 1266 } 1267 split->inputs = pnew; 1268 split->inputs_capacity = new_cap; 1269 } 1270 1271 static void ggml_backend_sched_graph_inputs_grow(ggml_backend_sched_t sched) { 1272 int new_cap = GGML_SCHED_MAX_SPLIT_INPUTS; 1273 if (sched->graph_inputs_capacity > 0) { 1274 new_cap = 2*sched->graph_inputs_capacity; 1275 GGML_LOG_DEBUG("%s: increasing graph inputs capacity from %d to %d\n", __func__, sched->graph_inputs_capacity, new_cap); 1276 } 1277 auto * pnew = (struct ggml_tensor **) realloc((void *) sched->graph_inputs, new_cap * sizeof(struct ggml_tensor *)); 1278 if (pnew == NULL) { 1279 GGML_LOG_ERROR("%s: failed to allocate %zu bytes\n", __func__, new_cap * sizeof(struct ggml_tensor *)); 1280 GGML_ABORT("failed to grow graph inputs container"); 1281 } 1282 sched->graph_inputs = pnew; 1283 sched->graph_inputs_capacity = new_cap; 1284 } 1285 1286 // returns the priority of the backend, lower id is higher priority 1287 static int ggml_backend_sched_backend_id(ggml_backend_sched_t sched, ggml_backend_t backend) { 1288 for (int i = 0; i < sched->n_backends; i++) { 1289 if (sched->backends[i] == backend) { 1290 return i; 1291 } 1292 } 1293 return -1; 1294 } 1295 1296 static int ggml_backend_sched_backend_from_buffer(ggml_backend_sched_t sched, const struct ggml_tensor * tensor, const struct ggml_tensor * op) { 1297 ggml_backend_buffer_t buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 1298 if (buffer == NULL) { 1299 return -1; 1300 } 1301 1302 // find highest prio backend that supports the buffer type and the op 1303 for (int i = 0; i < sched->n_backends; i++) { 1304 if (ggml_backend_supports_buft(sched->backends[i], buffer->buft) && 1305 ggml_backend_supports_op(sched->backends[i], op)) { 1306 return i; 1307 } 1308 } 1309 1310 #ifndef NDEBUG 1311 GGML_LOG_DEBUG("%s: warning: no backend supports op %s with a weight with buffer type %s used in tensor %s, the weight will need to be copied\n", 1312 __func__, ggml_op_desc(tensor), ggml_backend_buffer_name(buffer), tensor->name); 1313 #endif 1314 1315 return -1; 1316 } 1317 1318 #if 0 1319 #define GGML_SCHED_MAX_SPLITS_DEBUG 4096 1320 static char causes[GGML_DEFAULT_GRAPH_SIZE*16 + GGML_SCHED_MAX_SPLITS_DEBUG*GGML_SCHED_MAX_SPLIT_INPUTS][128]; // debug only 1321 #define SET_CAUSE(node, ...) sprintf(causes[hash_id(node)], __VA_ARGS__) 1322 #define GET_CAUSE(node) causes[hash_id(node)] 1323 #else 1324 #define SET_CAUSE(node, ...) 1325 #define GET_CAUSE(node) "" 1326 #endif 1327 1328 // returns the backend that should be used for the node based on the current locations 1329 static int ggml_backend_sched_backend_id_from_cur(ggml_backend_sched_t sched, struct ggml_tensor * tensor) { 1330 // assign pre-allocated nodes to their backend 1331 int cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor, tensor); 1332 if (cur_backend_id != -1) { 1333 SET_CAUSE(tensor, "1.dst"); 1334 return cur_backend_id; 1335 } 1336 1337 // view_src 1338 if (tensor->view_src != NULL) { 1339 cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor->view_src, tensor); 1340 if (cur_backend_id != -1) { 1341 SET_CAUSE(tensor, "1.vsrc"); 1342 return cur_backend_id; 1343 } 1344 } 1345 1346 if (tensor->buffer || (tensor->view_src && tensor->view_src->buffer)) { 1347 // since the tensor is pre-allocated, it cannot be moved to another backend 1348 ggml_backend_buffer_t buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer; 1349 GGML_ABORT("pre-allocated tensor (%s) in a buffer (%s) that cannot run the operation (%s)", tensor->name, ggml_backend_buffer_name(buffer), ggml_op_name(tensor->op)); 1350 } 1351 1352 // graph input 1353 if (tensor->flags & GGML_TENSOR_FLAG_INPUT) { 1354 cur_backend_id = sched->n_backends - 1; // last backend (assumed CPU) 1355 SET_CAUSE(tensor, "1.inp"); 1356 return cur_backend_id; 1357 } 1358 1359 // operations with weights are preferably run on the same backend as the weights 1360 // TODO: there are exceptions (see below) - not an ideal solution 1361 bool allow = true; 1362 1363 // skip ROPE since the rope freqs tensor is too small to choose a backend based on it 1364 allow = allow && tensor->op != GGML_OP_ROPE; 1365 1366 // skip FLASH_ATTN_EXT since the sinks tensor is too small to choose a based based on it 1367 allow = allow && tensor->op != GGML_OP_FLASH_ATTN_EXT; 1368 1369 if (allow) { 1370 for (int i = 0; i < GGML_MAX_SRC; i++) { 1371 const struct ggml_tensor * src = tensor->src[i]; 1372 if (src == NULL) { 1373 continue; 1374 } 1375 if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { 1376 int src_backend_id = ggml_backend_sched_backend_from_buffer(sched, src, tensor); 1377 // check if a backend with higher prio wants to offload the op 1378 if (sched->op_offload && src_backend_id == sched->n_backends - 1 && ggml_backend_buffer_is_host(src->buffer)) { 1379 for (int b = 0; b < src_backend_id; b++) { 1380 if (ggml_backend_supports_op(sched->backends[b], tensor) && ggml_backend_offload_op(sched->backends[b], tensor)) { 1381 SET_CAUSE(tensor, "1.off"); 1382 return b; 1383 } 1384 } 1385 } 1386 SET_CAUSE(tensor, "1.wgt%d", i); 1387 return src_backend_id; 1388 } 1389 } 1390 } 1391 1392 return -1; 1393 } 1394 1395 static char * fmt_size(size_t size) { 1396 static char buffer[128]; 1397 if (size >= 1024*1024) { 1398 snprintf(buffer, sizeof(buffer), "%zuM", size/1024/1024); 1399 } else { 1400 snprintf(buffer, sizeof(buffer), "%zuK", size/1024); 1401 } 1402 return buffer; 1403 } 1404 1405 static void ggml_backend_sched_print_assignments(ggml_backend_sched_t sched, struct ggml_cgraph * graph) { 1406 int cur_split = 0; 1407 for (int i = 0; i < graph->n_nodes; i++) { 1408 if (cur_split < sched->n_splits && i == sched->splits[cur_split].i_start) { 1409 ggml_backend_t split_backend = sched->backends[sched->splits[cur_split].backend_id]; 1410 GGML_LOG_DEBUG("\n## SPLIT #%d: %s # %d inputs", cur_split, ggml_backend_name(split_backend), 1411 sched->splits[cur_split].n_inputs); 1412 for (int j = 0; j < sched->splits[cur_split].n_inputs; j++) { 1413 if (j == 0) { 1414 GGML_LOG_DEBUG(": "); 1415 } 1416 GGML_LOG_DEBUG("[%s (%5.5s)] ", sched->splits[cur_split].inputs[j]->name, 1417 fmt_size(ggml_nbytes(sched->splits[cur_split].inputs[j]))); 1418 } 1419 GGML_LOG_DEBUG("\n"); 1420 cur_split++; 1421 } 1422 struct ggml_tensor * node = graph->nodes[i]; 1423 if (ggml_is_view_op(node->op)) { 1424 continue; 1425 } 1426 if (sched->debug > 1) { 1427 ggml_backend_t tensor_backend = ggml_backend_sched_get_tensor_backend(sched, node); 1428 GGML_LOG_DEBUG("node #%3d (%10.10s): %20.20s (%5.5s) [%5.5s %8.8s] use=%d,c=%d:", i, ggml_op_desc(node), node->name, 1429 fmt_size(ggml_nbytes(node)), tensor_backend ? ggml_backend_name(tensor_backend) : "NULL", GET_CAUSE(node), 1430 graph->use_counts[ggml_hash_find(&graph->visited_hash_set, node)], node->flags & GGML_TENSOR_FLAG_COMPUTE ? 1 : 0); 1431 for (int j = 0; j < GGML_MAX_SRC; j++) { 1432 struct ggml_tensor * src = node->src[j]; 1433 if (src == NULL) { 1434 continue; 1435 } 1436 ggml_backend_t src_backend = ggml_backend_sched_get_tensor_backend(sched, src); 1437 GGML_LOG_DEBUG(" %20.20s (%5.5s) [%5.5s %8.8s]", src->name, 1438 fmt_size(ggml_nbytes(src)), src_backend ? ggml_backend_name(src_backend) : "NULL", GET_CAUSE(src)); 1439 } 1440 GGML_LOG_DEBUG("\n"); 1441 } 1442 } 1443 } 1444 1445 static bool ggml_backend_sched_buffer_supported(ggml_backend_sched_t sched, struct ggml_tensor * t, int backend_id) { 1446 ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer; 1447 ggml_backend_buffer_type_t buft = NULL; 1448 1449 if (buf) { 1450 // the tensor is already allocated 1451 buft = buf->buft; 1452 } else { 1453 // see if the tensor already has a backend assigned, and use the buffer type of that backend 1454 int tensor_backend_id = tensor_backend_id(t); 1455 if (tensor_backend_id == -1 && t->view_src) { 1456 tensor_backend_id = tensor_backend_id(t->view_src); 1457 } 1458 if (tensor_backend_id != -1) { 1459 buft = sched->bufts[tensor_backend_id]; 1460 } 1461 } 1462 1463 return buft != NULL && ggml_backend_supports_buft(sched->backends[backend_id], buft); 1464 } 1465 1466 static void ggml_backend_sched_set_if_supported(ggml_backend_sched_t sched, struct ggml_tensor * node, int cur_backend_id, int * node_backend_id) { 1467 if (ggml_backend_supports_op(sched->backends[cur_backend_id], node)) { 1468 *node_backend_id = cur_backend_id; 1469 SET_CAUSE(node, "2.sup"); 1470 } 1471 } 1472 1473 // assigns backends to ops and splits the graph into subgraphs that can be computed on the same backend 1474 void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) { 1475 // reset splits 1476 sched->n_splits = 0; 1477 sched->n_graph_inputs = 0; 1478 sched->is_reset = false; 1479 1480 struct ggml_init_params params = { 1481 /* .mem_size = */ sched->context_buffer_size, 1482 /* .mem_buffer = */ sched->context_buffer, 1483 /* .no_alloc = */ true 1484 }; 1485 1486 ggml_free(sched->ctx); 1487 1488 sched->ctx = ggml_init(params); 1489 if (sched->ctx == NULL) { 1490 GGML_ABORT("%s: failed to initialize context\n", __func__); 1491 } 1492 1493 graph->uid = ggml_graph_next_uid(); 1494 1495 // pass 1: assign backends to ops with pre-allocated inputs 1496 for (int i = 0; i < graph->n_leafs; i++) { 1497 struct ggml_tensor * leaf = graph->leafs[i]; 1498 int * leaf_backend_id = &tensor_backend_id(leaf); 1499 // do not overwrite user assignments 1500 if (*leaf_backend_id == -1) { 1501 *leaf_backend_id = ggml_backend_sched_backend_id_from_cur(sched, leaf); 1502 } 1503 } 1504 1505 for (int i = 0; i < graph->n_nodes; i++) { 1506 struct ggml_tensor * node = graph->nodes[i]; 1507 int * node_backend_id = &tensor_backend_id(node); 1508 // do not overwrite user assignments 1509 if (*node_backend_id == -1) { 1510 *node_backend_id = ggml_backend_sched_backend_id_from_cur(sched, node); 1511 1512 #if 0 1513 // src 1514 if (node->op == GGML_OP_NONE) { 1515 continue; 1516 } 1517 1518 for (int j = 0; j < GGML_MAX_SRC; j++) { 1519 struct ggml_tensor * src = node->src[j]; 1520 if (src == NULL) { 1521 continue; 1522 } 1523 int * src_backend_id = &tensor_backend_id(src); 1524 if (*src_backend_id == -1) { 1525 *src_backend_id = ggml_backend_sched_backend_id_from_cur(sched, src); 1526 } 1527 } 1528 #endif 1529 } 1530 } 1531 1532 // pass 2: expand current backend assignments 1533 // assign the same backend to adjacent nodes 1534 // expand gpu backends (i.e. non last prio) up and down, ignoring cpu (the lowest priority backend) 1535 // thus, cpu will never be used unless weights are on cpu, or there are no gpu ops between cpu ops 1536 // ops unsupported by the backend being expanded will be left unassigned so that they can be assigned later when the locations of its inputs are known 1537 // expand gpu down 1538 { 1539 int cur_backend_id = -1; 1540 for (int i = 0; i < graph->n_nodes; i++) { 1541 struct ggml_tensor * node = graph->nodes[i]; 1542 if (ggml_is_view_op(node->op)) { 1543 continue; 1544 } 1545 int * node_backend_id = &tensor_backend_id(node); 1546 if (*node_backend_id != -1) { 1547 if (*node_backend_id == sched->n_backends - 1) { 1548 // skip cpu (lowest prio backend) 1549 cur_backend_id = -1; 1550 } else { 1551 cur_backend_id = *node_backend_id; 1552 } 1553 } else if (cur_backend_id != -1) { 1554 ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id); 1555 } 1556 } 1557 } 1558 // expand gpu up 1559 { 1560 int cur_backend_id = -1; 1561 for (int i = graph->n_nodes - 1; i >= 0; i--) { 1562 struct ggml_tensor * node = graph->nodes[i]; 1563 if (ggml_is_view_op(node->op)) { 1564 continue; 1565 } 1566 int * node_backend_id = &tensor_backend_id(node); 1567 if (*node_backend_id != -1) { 1568 if (*node_backend_id == sched->n_backends - 1) { 1569 // skip cpu (lowest prio backend) 1570 cur_backend_id = -1; 1571 } else { 1572 cur_backend_id = *node_backend_id; 1573 } 1574 } else if (cur_backend_id != -1) { 1575 ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id); 1576 } 1577 } 1578 } 1579 // expand rest down 1580 { 1581 int cur_backend_id = -1; 1582 for (int i = 0; i < graph->n_nodes; i++) { 1583 struct ggml_tensor * node = graph->nodes[i]; 1584 if (ggml_is_view_op(node->op)) { 1585 continue; 1586 } 1587 int * node_backend_id = &tensor_backend_id(node); 1588 if (*node_backend_id != -1) { 1589 cur_backend_id = *node_backend_id; 1590 } else if (cur_backend_id != -1) { 1591 ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id); 1592 } 1593 } 1594 } 1595 // expand rest up 1596 { 1597 int cur_backend_id = -1; 1598 for (int i = graph->n_nodes - 1; i >= 0; i--) { 1599 struct ggml_tensor * node = graph->nodes[i]; 1600 if (ggml_is_view_op(node->op)) { 1601 continue; 1602 } 1603 int * node_backend_id = &tensor_backend_id(node); 1604 if (*node_backend_id != -1) { 1605 cur_backend_id = *node_backend_id; 1606 } else if (cur_backend_id != -1) { 1607 ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id); 1608 } 1609 } 1610 } 1611 1612 // pass 3: upgrade nodes to higher prio backends with compatible buffer types 1613 // if the tensor is already in the same buffer type (*) as another higher priority backend, we should move it there 1614 // however, we also need to verify that the sources are in compatible buffer types 1615 // (*) the actual requirement is more relaxed, the buffer type of the backend should be supported by all the users of this tensor further down the graph 1616 // however, this is slow to verify, so we have a more strict requirement that the buffer type is the same 1617 // this is not uncommon since multiple backends can use host memory, with the same buffer type (eg. BLAS and CPU) 1618 // additionally, set remaining unassigned nodes to the backend with the most supported inputs 1619 // only nodes that could not be assigned during expansion due to the backend not supporting the op should be unassigned at this point 1620 for (int i = 0; i < graph->n_nodes; i++) { 1621 struct ggml_tensor * node = graph->nodes[i]; 1622 if (ggml_is_view_op(node->op)) { 1623 continue; 1624 } 1625 int * node_backend_id = &tensor_backend_id(node); 1626 if (*node_backend_id == -1) { 1627 // unassigned node: find the backend with the most supported inputs 1628 int n_supported_best = -1; 1629 for (int b = 0; b < sched->n_backends; b++) { 1630 if (ggml_backend_supports_op(sched->backends[b], node)) { 1631 int n_supported = 0; 1632 for (int j = 0; j < GGML_MAX_SRC; j++) { 1633 struct ggml_tensor * src = node->src[j]; 1634 if (src == NULL) { 1635 continue; 1636 } 1637 if ((tensor_backend_id(src) != -1 || tensor_backend_id(src->view_src) != -1) && ggml_backend_sched_buffer_supported(sched, src, b)) { 1638 n_supported++; 1639 } 1640 } 1641 if (n_supported > n_supported_best) { 1642 n_supported_best = n_supported; 1643 *node_backend_id = b; 1644 SET_CAUSE(node, "3.best"); 1645 } 1646 } 1647 } 1648 } else { 1649 // assigned node: upgrade to higher prio backend if possible 1650 for (int b = 0; b < *node_backend_id; b++) { 1651 if (sched->bufts[b] == sched->bufts[*node_backend_id] && ggml_backend_supports_op(sched->backends[b], node)) { 1652 bool supported = true; 1653 for (int j = 0; j < GGML_MAX_SRC; j++) { 1654 struct ggml_tensor * src = node->src[j]; 1655 if (src == NULL) { 1656 continue; 1657 } 1658 if (!ggml_backend_sched_buffer_supported(sched, src, b)) { 1659 supported = false; 1660 break; 1661 } 1662 } 1663 if (supported) { 1664 *node_backend_id = b; 1665 SET_CAUSE(node, "3.upg"); 1666 break; 1667 } 1668 } 1669 } 1670 } 1671 } 1672 1673 // pass 4: assign backends to remaining src from dst and view_src 1674 for (int i = 0; i < graph->n_nodes; i++) { 1675 struct ggml_tensor * node = graph->nodes[i]; 1676 int * cur_backend_id = &tensor_backend_id(node); 1677 if (node->view_src != NULL && *cur_backend_id == -1) { 1678 *cur_backend_id = tensor_backend_id(node->view_src); 1679 SET_CAUSE(node, "4.vsrc"); 1680 } 1681 for (int j = 0; j < GGML_MAX_SRC; j++) { 1682 struct ggml_tensor * src = node->src[j]; 1683 if (src == NULL) { 1684 continue; 1685 } 1686 int * src_backend_id = &tensor_backend_id(src); 1687 if (*src_backend_id == -1) { 1688 if (src->view_src != NULL) { 1689 // views are always on the same backend as the source 1690 *src_backend_id = tensor_backend_id(src->view_src); 1691 SET_CAUSE(src, "4.vsrc"); 1692 } else { 1693 *src_backend_id = *cur_backend_id; 1694 SET_CAUSE(src, "4.cur"); 1695 } 1696 } 1697 } 1698 // if the node is still unassigned, assign it to the first backend that supports it 1699 for (int b = 0; b < sched->n_backends && *cur_backend_id == -1; b++) { 1700 ggml_backend_sched_set_if_supported(sched, node, b, cur_backend_id); 1701 } 1702 GGML_ASSERT(*cur_backend_id != -1); 1703 } 1704 1705 // pass 5: split graph, find tensors that need to be copied 1706 { 1707 int i_split = 0; 1708 struct ggml_backend_sched_split * split = &sched->splits[0]; 1709 // find the backend of the first split, skipping view ops 1710 int i = 0; 1711 for (; i < graph->n_nodes; i++) { 1712 struct ggml_tensor * node = graph->nodes[i]; 1713 if (!ggml_is_view_op(node->op)) { 1714 split->backend_id = tensor_backend_id(node); 1715 break; 1716 } 1717 } 1718 split->i_start = 0; 1719 split->n_inputs = 0; 1720 int cur_backend_id = split->backend_id; 1721 for (; i < graph->n_nodes; i++) { 1722 struct ggml_tensor * node = graph->nodes[i]; 1723 1724 if (ggml_is_view_op(node->op)) { 1725 continue; 1726 } 1727 1728 const int node_backend_id = tensor_backend_id(node); 1729 1730 GGML_ASSERT(node_backend_id != -1); // all nodes should be assigned by now, this can happen if there is no CPU fallback 1731 1732 // check if we should start a new split based on the sources of the current node 1733 bool need_new_split = false; 1734 if (node_backend_id == cur_backend_id && split->n_inputs > 0) { 1735 for (int j = 0; j < GGML_MAX_SRC; j++) { 1736 struct ggml_tensor * src = node->src[j]; 1737 if (src == NULL) { 1738 continue; 1739 } 1740 // check if a weight is on a different and incompatible backend 1741 // by starting a new split, the memory of the previously offloaded weights can be reused 1742 if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) { 1743 int src_backend_id = tensor_backend_id(src); 1744 if (src_backend_id != cur_backend_id && !ggml_backend_sched_buffer_supported(sched, src, cur_backend_id)) { 1745 need_new_split = true; 1746 break; 1747 } 1748 } 1749 } 1750 } 1751 1752 if (node_backend_id != cur_backend_id || need_new_split) { 1753 split->i_end = i; 1754 i_split++; 1755 if (i_split >= sched->splits_capacity) { 1756 int old_cap = sched->splits_capacity; 1757 sched->splits_capacity *= 2; 1758 sched->splits = (ggml_backend_sched_split *) 1759 realloc(sched->splits, sched->splits_capacity * sizeof(struct ggml_backend_sched_split)); 1760 GGML_ASSERT(sched->splits != NULL); 1761 for (int k = old_cap; k < sched->splits_capacity; k++) { 1762 memset(&sched->splits[k], 0, sizeof(struct ggml_backend_sched_split)); 1763 } 1764 } 1765 split = &sched->splits[i_split]; 1766 split->backend_id = node_backend_id; 1767 split->i_start = i; 1768 split->n_inputs = 0; 1769 cur_backend_id = node_backend_id; 1770 } 1771 1772 // find inputs that are not on the same backend 1773 for (int j = 0; j < GGML_MAX_SRC; j++) { 1774 struct ggml_tensor * src = node->src[j]; 1775 if (src == NULL) { 1776 continue; 1777 } 1778 1779 size_t src_id = hash_id(src); 1780 const int src_backend_id = sched->hv_tensor_backend_ids[src_id]; 1781 GGML_ASSERT(src_backend_id != -1); // all inputs should be assigned by now 1782 1783 if (src_backend_id != cur_backend_id && !ggml_backend_sched_buffer_supported(sched, src, cur_backend_id)) { 1784 // create a copy of the input in the split's backend 1785 if (tensor_id_copy(src_id, cur_backend_id, 0) == NULL) { 1786 ggml_backend_t backend = sched->backends[cur_backend_id]; 1787 for (int c = 0; c < sched->n_copies; c++) { 1788 struct ggml_tensor * tensor_copy = ggml_dup_tensor_layout(sched->ctx, src); 1789 ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), src->name, c); 1790 if (sched->n_copies > 1) { 1791 ggml_set_input(tensor_copy); 1792 ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor 1793 } 1794 tensor_id_copy(src_id, cur_backend_id, c) = tensor_copy; 1795 SET_CAUSE(tensor_copy, "4.cpy"); 1796 } 1797 int n_inputs = split->n_inputs++; 1798 if (n_inputs >= split->inputs_capacity) { 1799 ggml_backend_sched_split_inputs_grow(split); 1800 } 1801 split->inputs[n_inputs] = src; 1802 } 1803 node->src[j] = tensor_id_copy(src_id, cur_backend_id, sched->cur_copy); 1804 } 1805 } 1806 } 1807 split->i_end = graph->n_nodes; 1808 sched->n_splits = i_split + 1; 1809 } 1810 1811 if (sched->debug) { 1812 ggml_backend_sched_print_assignments(sched, graph); 1813 } 1814 1815 // pass 6: collect all input tensors into graph_inputs 1816 // this includes inputs not consumed by any node (e.g. the embeddings input of a text-only batch) so that 1817 // the graph composition does not depend on which inputs are used, which would otherwise cause graph 1818 // reallocations when switching between different types of batches [GGML_SCHED_DEBUG_REALLOC] 1819 if (sched->n_copies > 1) { 1820 for (int i = 0; i < graph->n_leafs; i++) { 1821 struct ggml_tensor * leaf = graph->leafs[i]; 1822 if ((leaf->flags & GGML_TENSOR_FLAG_INPUT) == 0) { 1823 continue; 1824 } 1825 1826 const size_t leaf_id = hash_id(leaf); 1827 const int leaf_backend_id = tensor_backend_id(leaf); 1828 GGML_ASSERT(leaf_backend_id != -1); // all leafs should be assigned by now 1829 1830 if (tensor_id_copy(leaf_id, leaf_backend_id, 0) == NULL) { 1831 ggml_backend_t backend = sched->backends[leaf_backend_id]; 1832 for (int c = 0; c < sched->n_copies; c++) { 1833 struct ggml_tensor * tensor_copy; 1834 if (c == sched->cur_copy) { 1835 tensor_copy = leaf; // use the original tensor as the current copy 1836 } else { 1837 tensor_copy = ggml_dup_tensor_layout(sched->ctx, leaf); 1838 ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), leaf->name, c); 1839 } 1840 ggml_set_input(tensor_copy); 1841 ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor 1842 tensor_id_copy(leaf_id, leaf_backend_id, c) = tensor_copy; 1843 SET_CAUSE(tensor_copy, "6.cpy"); 1844 } 1845 } 1846 1847 int n_graph_inputs = sched->n_graph_inputs++; 1848 if (n_graph_inputs >= sched->graph_inputs_capacity) { 1849 ggml_backend_sched_graph_inputs_grow(sched); 1850 } 1851 sched->graph_inputs[n_graph_inputs] = leaf; 1852 } 1853 } 1854 1855 // swap node_backend_ids and leaf _backend_ids with prevs 1856 { 1857 int * tmp = sched->node_backend_ids; 1858 sched->node_backend_ids = sched->prev_node_backend_ids; 1859 sched->prev_node_backend_ids = tmp; 1860 1861 tmp = sched->leaf_backend_ids; 1862 sched->leaf_backend_ids = sched->prev_leaf_backend_ids; 1863 sched->prev_leaf_backend_ids = tmp; 1864 } 1865 1866 // optimize the split graphs and collect the allocation dependencies added by the backends 1867 // this needs to happen before we make graph_copy, so they are in sync 1868 // TODO: this may create many small allocations in the scheduler, restructure to use a flat array 1869 std::unordered_map> alloc_deps; 1870 1871 struct ggml_backend_graph_optimize_params opt_params = { 1872 /* .add_alloc_dep = */ [](void * user_data, ggml_tensor * tensor, ggml_tensor * until) { 1873 auto & deps = *(std::unordered_map> *) user_data; 1874 std::vector & keep = deps[until]; 1875 if (std::find(keep.begin(), keep.end(), tensor) == keep.end()) { 1876 keep.push_back(tensor); 1877 } 1878 }, 1879 /* .user_data = */ &alloc_deps, 1880 }; 1881 1882 for (int i = 0; i < sched->n_splits; i++) { 1883 struct ggml_backend_sched_split * split = &sched->splits[i]; 1884 split->graph = ggml_graph_view(graph, split->i_start, split->i_end); 1885 1886 ggml_backend_graph_optimize(sched->backends[split->backend_id], &split->graph, &opt_params); 1887 } 1888 1889 // each dep is added to graph_copy as a GGML_OP_NONE node with the kept tensors as srcs 1890 int n_dep_nodes = 0; 1891 for (const auto & it : alloc_deps) { 1892 n_dep_nodes += (it.second.size() + GGML_MAX_SRC - 1) / GGML_MAX_SRC; 1893 } 1894 1895 int total_inputs = sched->n_graph_inputs; 1896 for (int i = 0; i < sched->n_splits; i++) { 1897 total_inputs += sched->splits[i].n_inputs; 1898 } 1899 int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes; 1900 1901 // remember the actual graph_size for performing reallocation checks later 1902 sched->prev_graph_size = sched->graph_size; 1903 sched->graph_size = graph_size; 1904 1905 if (sched->graph.size < graph_size) { 1906 sched->graph.size = graph_size; 1907 sched->graph.nodes = (ggml_tensor **) realloc(sched->graph.nodes, graph_size * sizeof(struct ggml_tensor *)); 1908 sched->graph.leafs = (ggml_tensor **) realloc(sched->graph.leafs, graph_size * sizeof(struct ggml_tensor *)); 1909 GGML_ASSERT(sched->graph.nodes != NULL); 1910 GGML_ASSERT(sched->graph.leafs != NULL); 1911 } 1912 sched->graph.n_nodes = 0; 1913 sched->graph.n_leafs = 0; 1914 1915 struct ggml_cgraph * graph_copy = &sched->graph; 1916 1917 int n_dep_nodes_added = 0; 1918 1919 for (int i = 0; i < sched->n_splits; i++) { 1920 struct ggml_backend_sched_split * split = &sched->splits[i]; 1921 1922 // add inputs to the graph copy so that they are allocated by ggml-alloc at the start of the split 1923 for (int j = 0; j < split->n_inputs; j++) { 1924 assert(graph_copy->size > (graph_copy->n_nodes + 1)); 1925 1926 struct ggml_tensor * input = split->inputs[j]; 1927 const size_t input_id = hash_id(input); 1928 struct ggml_tensor * input_cpy = tensor_id_copy(input_id, split->backend_id, sched->cur_copy); 1929 1930 // add a dependency to the input source so that it is not freed before the copy is done 1931 struct ggml_tensor * input_dep = ggml_view_tensor(sched->ctx, input); 1932 input_dep->src[0] = input; 1933 sched->node_backend_ids[graph_copy->n_nodes] = sched->hv_tensor_backend_ids[input_id]; 1934 graph_copy->nodes[graph_copy->n_nodes++] = input_dep; 1935 1936 // add a dependency to the input copy so that it is allocated at the start of the split 1937 sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id; 1938 graph_copy->nodes[graph_copy->n_nodes++] = input_cpy; 1939 } 1940 1941 for (int j = split->i_start; j < split->i_end; j++) { 1942 assert(graph_copy->size > graph_copy->n_nodes); 1943 sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]); 1944 graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j]; 1945 1946 if (alloc_deps.empty()) { 1947 continue; 1948 } 1949 1950 // add a dependency node so that the kept tensors are not freed before this node is computed 1951 auto it = alloc_deps.find(graph->nodes[j]); 1952 if (it != alloc_deps.end()) { 1953 const std::vector & keep = it->second; 1954 for (size_t k = 0; k < keep.size(); k += GGML_MAX_SRC) { 1955 struct ggml_tensor * dep = ggml_view_tensor(sched->ctx, keep[k]); 1956 for (size_t s = 0; s < GGML_MAX_SRC && k + s < keep.size(); s++) { 1957 dep->src[s] = keep[k + s]; 1958 } 1959 assert(graph_copy->size > graph_copy->n_nodes); 1960 sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id; 1961 graph_copy->nodes[graph_copy->n_nodes++] = dep; 1962 n_dep_nodes_added++; 1963 } 1964 } 1965 } 1966 } 1967 1968 // a mismatch means a backend added a dep with an `until` tensor that is not a node of the optimized graph 1969 GGML_ASSERT(n_dep_nodes_added == n_dep_nodes); 1970 1971 if (sched->n_copies > 1) { 1972 // add input copies as leafs so that they are allocated first 1973 for (int i = 0; i < sched->n_graph_inputs; i++) { 1974 struct ggml_tensor * input = sched->graph_inputs[i]; 1975 size_t id = hash_id(input); 1976 int backend_id = tensor_backend_id(input); 1977 for (int c = 0; c < sched->n_copies; c++) { 1978 struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c); 1979 sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id; 1980 assert(graph_copy->size > graph_copy->n_leafs); 1981 graph_copy->leafs[graph_copy->n_leafs++] = input_cpy; 1982 } 1983 } 1984 1985 for (int i = 0; i < sched->n_splits; i++) { 1986 struct ggml_backend_sched_split * split = &sched->splits[i]; 1987 int backend_id = split->backend_id; 1988 for (int j = 0; j < split->n_inputs; j++) { 1989 struct ggml_tensor * input = split->inputs[j]; 1990 size_t id = hash_id(input); 1991 for (int c = 0; c < sched->n_copies; c++) { 1992 struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c); 1993 sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id; 1994 assert(graph_copy->size > graph_copy->n_leafs); 1995 graph_copy->leafs[graph_copy->n_leafs++] = input_cpy; 1996 } 1997 } 1998 } 1999 } 2000 2001 // add leafs from the original graph 2002 for (int i = 0; i < graph->n_leafs; i++) { 2003 struct ggml_tensor * leaf = graph->leafs[i]; 2004 sched->leaf_backend_ids[graph_copy->n_leafs] = tensor_backend_id(leaf); 2005 assert(graph_copy->size > graph_copy->n_leafs); 2006 graph_copy->leafs[graph_copy->n_leafs++] = leaf; 2007 } 2008 2009 // set ids for all splits 2010 for (int i = 0; i < sched->n_splits; ++i) { 2011 sched->splits[i].graph.uid = ggml_graph_next_uid(); 2012 } 2013 } 2014 2015 static bool ggml_backend_sched_alloc_splits(ggml_backend_sched_t sched) { 2016 bool backend_ids_changed = false; 2017 for (int i = 0; i < sched->graph.n_nodes; i++) { 2018 if (sched->node_backend_ids[i] != sched->prev_node_backend_ids[i] && 2019 sched->bufts[sched->node_backend_ids[i]] != sched->bufts[sched->prev_node_backend_ids[i]]) { 2020 backend_ids_changed = true; 2021 break; 2022 } 2023 } 2024 if (!backend_ids_changed) { 2025 for (int i = 0; i < sched->graph.n_leafs; i++) { 2026 if (sched->leaf_backend_ids[i] != sched->prev_leaf_backend_ids[i] && 2027 sched->bufts[sched->leaf_backend_ids[i]] != sched->bufts[sched->prev_leaf_backend_ids[i]]) { 2028 backend_ids_changed = true; 2029 break; 2030 } 2031 } 2032 } 2033 2034 // allocate graph 2035 if (backend_ids_changed || !ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) { 2036 #ifndef NDEBUG 2037 GGML_LOG_DEBUG("%s: failed to allocate graph, reserving (backend_ids_changed = %d)\n", __func__, backend_ids_changed); 2038 #endif 2039 2040 // a reallocation with an unchanged graph size means that the previous reservation was not sufficient 2041 const bool graph_size_changed = sched->prev_graph_size != sched->graph_size; 2042 2043 if (sched->callback_realloc != NULL) { 2044 sched->callback_realloc(sched, &sched->graph, backend_ids_changed, graph_size_changed, sched->callback_realloc_user_data); 2045 } 2046 2047 if (sched->debug_realloc > 0) { 2048 // we are interested only in situations where the graph was reallocated even though its size remained the same [GGML_SCHED_DEBUG_REALLOC] 2049 // example: https://github.com/ggml-org/llama.cpp/pull/17143 2050 const bool unexpected = !backend_ids_changed && !graph_size_changed; 2051 2052 if (unexpected || sched->debug_realloc > 1) { 2053 GGML_ABORT("%s: unexpected graph reallocation (graph size = %d, nodes = %d, leafs = %d), debug_realloc = %d\n", __func__, 2054 sched->graph_size, sched->graph.n_nodes, sched->graph.n_leafs, sched->debug_realloc); 2055 } 2056 } 2057 2058 // the re-allocation may cause the split inputs to be moved to a different address 2059 // synchronize without ggml_backend_sched_synchronize to avoid changing cur_copy 2060 for (int i = 0; i < sched->n_backends; i++) { 2061 ggml_backend_synchronize(sched->backends[i]); 2062 } 2063 2064 if (!ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids)) { 2065 GGML_LOG_ERROR("%s: failed to reserve graph buffers\n", __func__); 2066 return false; 2067 } 2068 if (!ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) { 2069 GGML_LOG_ERROR("%s: failed to allocate graph\n", __func__); 2070 return false; 2071 } 2072 } 2073 2074 return true; 2075 } 2076 2077 static bool ggml_backend_sched_is_host_weight(const struct ggml_tensor * t) { 2078 return t->buffer != NULL && 2079 ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && 2080 ggml_backend_buffer_is_host(t->buffer); 2081 } 2082 2083 static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) { 2084 const int split_backend_id = split->backend_id; 2085 ggml_backend_t split_backend = sched->backends[split_backend_id]; 2086 ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, input); 2087 struct ggml_tensor * input_cpy = tensor_copy(input, split_backend_id, sched->cur_copy); 2088 2089 if (input->flags & GGML_TENSOR_FLAG_INPUT) { 2090 // inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done 2091 if (sched->events[split_backend_id][sched->cur_copy] != NULL) { 2092 ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]); 2093 } else { 2094 ggml_backend_synchronize(split_backend); 2095 } 2096 ggml_backend_tensor_copy(input, input_cpy); 2097 return; 2098 } 2099 2100 // wait for the split backend to finish using the input before overwriting it 2101 if (sched->events[split_backend_id][sched->cur_copy] != NULL) { 2102 ggml_backend_event_wait(split_backend, sched->events[split_backend_id][sched->cur_copy]); 2103 } else { 2104 ggml_backend_synchronize(split_backend); 2105 } 2106 2107 if (sched->callback_copy != NULL && ggml_backend_sched_is_host_weight(input) && 2108 sched->callback_copy(split_backend, input, input_cpy, &split->graph, sched->callback_copy_user_data)) { 2109 return; 2110 } 2111 2112 // try async copy, but if not possible, we can still use a sync copy without synchronizing the dst backend, since we handle the synchronization here with multiple copies and events 2113 // TODO: add public function to facilitate this, since applications do not have direct access to the backend interface 2114 if (!split_backend->iface.cpy_tensor_async || !split_backend->iface.cpy_tensor_async(input_backend, split_backend, input, input_cpy)) { 2115 ggml_backend_synchronize(input_backend); 2116 if (sched->events[split_backend_id][sched->cur_copy] != NULL) { 2117 ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]); 2118 } else { 2119 ggml_backend_synchronize(split_backend); 2120 } 2121 ggml_backend_tensor_copy(input, input_cpy); 2122 } 2123 } 2124 2125 static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t sched) { 2126 GGML_ASSERT(sched); 2127 struct ggml_backend_sched_split * splits = sched->splits; 2128 2129 int prev_backend_id = -1; 2130 2131 for (int split_id = 0; split_id < sched->n_splits; split_id++) { 2132 struct ggml_backend_sched_split * split = &splits[split_id]; 2133 int split_backend_id = split->backend_id; 2134 ggml_backend_t split_backend = sched->backends[split_backend_id]; 2135 2136 // ensure the previous split's async work has completed before we start 2137 // this split, the allocator may have reused buffer regions across splits 2138 if (split->n_inputs == 0 && prev_backend_id >= 0 && prev_backend_id != split_backend_id) { 2139 if (sched->events[prev_backend_id][sched->cur_copy] != NULL) { 2140 ggml_backend_event_synchronize(sched->events[prev_backend_id][sched->cur_copy]); 2141 } else { 2142 ggml_backend_synchronize(sched->backends[prev_backend_id]); 2143 } 2144 } 2145 2146 // copy the input tensors to the split backend 2147 // the weights in host memory are copied last, so that the copy callback can read the other inputs of the split 2148 for (int input_id = 0; input_id < split->n_inputs; input_id++) { 2149 if (!ggml_backend_sched_is_host_weight(split->inputs[input_id])) { 2150 ggml_backend_sched_copy_input(sched, split, split->inputs[input_id]); 2151 } 2152 } 2153 for (int input_id = 0; input_id < split->n_inputs; input_id++) { 2154 if (ggml_backend_sched_is_host_weight(split->inputs[input_id])) { 2155 ggml_backend_sched_copy_input(sched, split, split->inputs[input_id]); 2156 } 2157 } 2158 2159 if (!sched->callback_eval) { 2160 enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &split->graph); 2161 if (ec != GGML_STATUS_SUCCESS) { 2162 return ec; 2163 } 2164 } else { 2165 // similar to ggml_backend_compare_graph_backend 2166 for (int j0 = 0; j0 < split->graph.n_nodes; j0++) { 2167 struct ggml_tensor * t = split->graph.nodes[j0]; 2168 2169 // check if the user needs data from this node 2170 bool need = sched->callback_eval(t, true, sched->callback_eval_user_data); 2171 2172 int j1 = j0; 2173 2174 // determine the range [j0, j1] of nodes that can be computed together 2175 while (!need && j1 < split->graph.n_nodes - 1) { 2176 t = split->graph.nodes[++j1]; 2177 need = sched->callback_eval(t, true, sched->callback_eval_user_data); 2178 } 2179 2180 struct ggml_cgraph gv = ggml_graph_view(&split->graph, j0, j1 + 1); 2181 2182 enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &gv); 2183 if (ec != GGML_STATUS_SUCCESS) { 2184 return ec; 2185 } 2186 2187 // TODO: pass backend to the callback, then the user can decide if they want to synchronize 2188 ggml_backend_synchronize(split_backend); 2189 2190 if (need && !sched->callback_eval(t, false, sched->callback_eval_user_data)) { 2191 break; 2192 } 2193 2194 j0 = j1; 2195 } 2196 } 2197 2198 // record the event of this split 2199 if (sched->events[split_backend_id][sched->cur_copy] != NULL) { 2200 ggml_backend_event_record(sched->events[split_backend_id][sched->cur_copy], split_backend); 2201 } 2202 2203 prev_backend_id = split_backend_id; 2204 } 2205 2206 return GGML_STATUS_SUCCESS; 2207 } 2208 2209 ggml_backend_sched_t ggml_backend_sched_new( 2210 ggml_backend_t * backends, 2211 ggml_backend_buffer_type_t * bufts, 2212 int n_backends, 2213 size_t graph_size, 2214 bool parallel, 2215 bool op_offload) { 2216 GGML_ASSERT(n_backends > 0); 2217 GGML_ASSERT(n_backends <= GGML_SCHED_MAX_BACKENDS); 2218 GGML_ASSERT(ggml_backend_dev_type(ggml_backend_get_device(backends[n_backends - 1])) == GGML_BACKEND_DEVICE_TYPE_CPU); 2219 2220 struct ggml_backend_sched * sched = (ggml_backend_sched *) calloc(1, sizeof(struct ggml_backend_sched)); 2221 2222 const char * GGML_SCHED_DEBUG = getenv("GGML_SCHED_DEBUG"); 2223 sched->debug = GGML_SCHED_DEBUG ? atoi(GGML_SCHED_DEBUG) : 0; 2224 2225 sched->debug_realloc = 0; 2226 #ifdef GGML_SCHED_NO_REALLOC 2227 sched->debug_realloc = 1; 2228 #endif 2229 const char * GGML_SCHED_DEBUG_REALLOC = getenv("GGML_SCHED_DEBUG_REALLOC"); 2230 sched->debug_realloc = GGML_SCHED_DEBUG_REALLOC ? atoi(GGML_SCHED_DEBUG_REALLOC) : sched->debug_realloc; 2231 2232 sched->n_backends = n_backends; 2233 sched->n_copies = parallel ? GGML_SCHED_MAX_COPIES : 1; 2234 2235 // initialize hash table 2236 // FIXME: needs to be size*2 to account for leafs (do it in graph_split instead) 2237 sched->hash_set = ggml_hash_set_new(graph_size); 2238 sched->hv_tensor_backend_ids = (int *) malloc(sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0])); 2239 sched->hv_tensor_copies = (ggml_tensor **) malloc(sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *)); 2240 2241 const size_t ggml_sched_max_splits = graph_size; // at most there is one split for each node in the graph 2242 const size_t nodes_size = graph_size + ggml_sched_max_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2; 2243 sched->node_backend_ids = (int *) calloc(nodes_size, sizeof(sched->node_backend_ids[0])); 2244 sched->leaf_backend_ids = (int *) calloc(nodes_size, sizeof(sched->leaf_backend_ids[0])); 2245 sched->prev_node_backend_ids = (int *) calloc(nodes_size, sizeof(sched->prev_node_backend_ids[0])); 2246 sched->prev_leaf_backend_ids = (int *) calloc(nodes_size, sizeof(sched->prev_leaf_backend_ids[0])); 2247 2248 sched->graph_size = 0; 2249 sched->prev_graph_size = 0; 2250 2251 sched->context_buffer_size = ggml_sched_max_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2*sizeof(struct ggml_tensor) + ggml_graph_overhead_custom(graph_size, false); 2252 sched->context_buffer = (char *) malloc(sched->context_buffer_size); 2253 2254 const int initial_splits_capacity = 16; 2255 sched->splits = (ggml_backend_sched_split *) calloc(initial_splits_capacity, sizeof(sched->splits[0])); 2256 sched->splits_capacity = initial_splits_capacity; 2257 2258 sched->graph_inputs_capacity = GGML_SCHED_MAX_SPLIT_INPUTS; 2259 sched->graph_inputs = (struct ggml_tensor **) calloc(sched->graph_inputs_capacity, sizeof(struct ggml_tensor *)); 2260 2261 for (int b = 0; b < n_backends; b++) { 2262 sched->backends[b] = backends[b]; 2263 sched->bufts[b] = bufts ? bufts[b] : ggml_backend_get_default_buffer_type(backends[b]); 2264 GGML_ASSERT(ggml_backend_supports_buft(backends[b], sched->bufts[b])); 2265 2266 if (sched->n_copies > 1) { 2267 for (int c = 0; c < sched->n_copies; c++) { 2268 sched->events[b][c] = ggml_backend_event_new(backends[b]->device); 2269 } 2270 } 2271 } 2272 2273 sched->galloc = ggml_gallocr_new_n(sched->bufts, n_backends); 2274 sched->op_offload = op_offload; 2275 2276 ggml_backend_sched_reset(sched); 2277 2278 return sched; 2279 } 2280 2281 void ggml_backend_sched_free(ggml_backend_sched_t sched) { 2282 if (sched == NULL) { 2283 return; 2284 } 2285 for (int b = 0; b < sched->n_backends; b++) { 2286 for (int c = 0; c < sched->n_copies; c++) { 2287 ggml_backend_event_free(sched->events[b][c]); 2288 } 2289 } 2290 ggml_gallocr_free(sched->galloc); 2291 ggml_free(sched->ctx); 2292 ggml_hash_set_free(&sched->hash_set); 2293 for (int i = 0; i < sched->splits_capacity; i++) { 2294 free(sched->splits[i].inputs); 2295 } 2296 free(sched->splits); 2297 free(sched->graph_inputs); 2298 free(sched->hv_tensor_backend_ids); 2299 free(sched->hv_tensor_copies); 2300 free(sched->node_backend_ids); 2301 free(sched->leaf_backend_ids); 2302 free(sched->prev_node_backend_ids); 2303 free(sched->prev_leaf_backend_ids); 2304 free(sched->context_buffer); 2305 free(sched->graph.nodes); 2306 free(sched->graph.leafs); 2307 free(sched); 2308 } 2309 2310 void ggml_backend_sched_reset(ggml_backend_sched_t sched) { 2311 GGML_ASSERT(sched); 2312 // reset state for the next run 2313 if (!sched->is_reset) { 2314 ggml_hash_set_reset(&sched->hash_set); 2315 memset(sched->hv_tensor_backend_ids, -1, sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0])); 2316 memset(sched->hv_tensor_copies, 0, sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *)); 2317 sched->is_reset = true; 2318 } 2319 sched->is_alloc = false; 2320 } 2321 2322 void ggml_backend_sched_reserve_size(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph, size_t * sizes) { 2323 GGML_ASSERT(sched); 2324 GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs); 2325 GGML_ASSERT(sizes); 2326 2327 ggml_backend_sched_reset(sched); 2328 2329 ggml_backend_sched_synchronize(sched); 2330 2331 ggml_backend_sched_split_graph(sched, measure_graph); 2332 2333 ggml_gallocr_reserve_n_size(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids, sizes); 2334 } 2335 2336 bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph) { 2337 GGML_ASSERT(sched); 2338 GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs); 2339 2340 ggml_backend_sched_synchronize(sched); 2341 2342 ggml_backend_sched_split_graph(sched, measure_graph); 2343 2344 if (!ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids)) { 2345 return false; 2346 } 2347 2348 ggml_backend_sched_reset(sched); 2349 2350 return true; 2351 } 2352 2353 bool ggml_backend_sched_alloc_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) { 2354 GGML_ASSERT(sched); 2355 GGML_ASSERT((int)sched->hash_set.size >= graph->n_nodes + graph->n_leafs); 2356 GGML_ASSERT(!sched->is_alloc); 2357 2358 sched->cur_copy = sched->next_copy; 2359 sched->next_copy = (sched->next_copy + 1) % sched->n_copies; 2360 2361 ggml_backend_sched_split_graph(sched, graph); 2362 2363 if (!ggml_backend_sched_alloc_splits(sched)) { 2364 return false; 2365 } 2366 2367 sched->is_alloc = true; 2368 2369 return true; 2370 } 2371 2372 enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph) { 2373 enum ggml_status err = ggml_backend_sched_graph_compute_async(sched, graph); 2374 ggml_backend_sched_synchronize(sched); 2375 return err; 2376 } 2377 2378 enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph) { 2379 GGML_ASSERT(sched); 2380 if (!sched->is_reset && !sched->is_alloc) { 2381 ggml_backend_sched_reset(sched); 2382 } 2383 2384 if (!sched->is_alloc) { 2385 if (!ggml_backend_sched_alloc_graph(sched, graph)) { 2386 return GGML_STATUS_ALLOC_FAILED; 2387 } 2388 } 2389 2390 return ggml_backend_sched_compute_splits(sched); 2391 } 2392 2393 void ggml_backend_sched_synchronize(ggml_backend_sched_t sched) { 2394 GGML_ASSERT(sched); 2395 for (int i = 0; i < sched->n_backends; i++) { 2396 ggml_backend_synchronize(sched->backends[i]); 2397 } 2398 if (!sched->is_alloc) { 2399 // if the graph is not already allocated, always use copy 0 after a synchronization 2400 // this ensures that during generation the same copy is used every time, 2401 // which avoids changes in the graph that could cause CUDA or other graphs to be disabled 2402 sched->next_copy = 0; 2403 } 2404 } 2405 2406 void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data) { 2407 GGML_ASSERT(sched); 2408 sched->callback_eval = callback; 2409 sched->callback_eval_user_data = user_data; 2410 } 2411 2412 void ggml_backend_sched_set_copy_callback(ggml_backend_sched_t sched, ggml_backend_sched_copy_callback callback, void * user_data) { 2413 GGML_ASSERT(sched); 2414 sched->callback_copy = callback; 2415 sched->callback_copy_user_data = user_data; 2416 } 2417 2418 void ggml_backend_sched_set_realloc_callback(ggml_backend_sched_t sched, ggml_backend_sched_realloc_callback callback, void * user_data) { 2419 GGML_ASSERT(sched); 2420 sched->callback_realloc = callback; 2421 sched->callback_realloc_user_data = user_data; 2422 } 2423 2424 int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched) { 2425 GGML_ASSERT(sched); 2426 return sched->n_splits; 2427 } 2428 2429 int ggml_backend_sched_get_n_copies(ggml_backend_sched_t sched) { 2430 GGML_ASSERT(sched); 2431 return sched->n_copies; 2432 } 2433 2434 int ggml_backend_sched_get_n_backends(ggml_backend_sched_t sched) { 2435 GGML_ASSERT(sched); 2436 return sched->n_backends; 2437 } 2438 2439 ggml_backend_t ggml_backend_sched_get_backend(ggml_backend_sched_t sched, int i) { 2440 GGML_ASSERT(sched); 2441 GGML_ASSERT(i >= 0 && i < sched->n_backends); 2442 return sched->backends[i]; 2443 } 2444 2445 ggml_backend_buffer_type_t ggml_backend_sched_get_buffer_type(ggml_backend_sched_t sched, ggml_backend_t backend) { 2446 GGML_ASSERT(sched); 2447 int backend_index = ggml_backend_sched_backend_id(sched, backend); 2448 GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends); 2449 2450 return sched->bufts[backend_index]; 2451 } 2452 2453 size_t ggml_backend_sched_get_buffer_size(ggml_backend_sched_t sched, ggml_backend_t backend) { 2454 GGML_ASSERT(sched); 2455 int backend_index = ggml_backend_sched_backend_id(sched, backend); 2456 GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends); 2457 2458 return ggml_gallocr_get_buffer_size(sched->galloc, backend_index); 2459 } 2460 2461 void ggml_backend_sched_set_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend) { 2462 GGML_ASSERT(sched); 2463 int backend_index = ggml_backend_sched_backend_id(sched, backend); 2464 GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends); 2465 tensor_backend_id(node) = backend_index; 2466 SET_CAUSE(node, "usr"); 2467 sched->is_reset = false; 2468 } 2469 2470 ggml_backend_t ggml_backend_sched_get_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node) { 2471 GGML_ASSERT(sched); 2472 int backend_index = tensor_backend_id(node); 2473 if (backend_index == -1) { 2474 return NULL; 2475 } 2476 return sched->backends[backend_index]; 2477 } 2478 2479 // utils 2480 2481 bool ggml_op_alloc_size_may_expand(enum ggml_op op) { 2482 switch (op) { 2483 case GGML_OP_FLASH_ATTN_EXT: 2484 case GGML_OP_MUL_MAT: 2485 case GGML_OP_MUL_MAT_ID: 2486 case GGML_OP_CUMSUM: 2487 case GGML_OP_ARGSORT: 2488 case GGML_OP_TOP_K: 2489 case GGML_OP_ARGMAX: 2490 return true; 2491 default: 2492 return false; 2493 } 2494 } 2495 2496 enum ggml_status ggml_backend_view_init(struct ggml_tensor * tensor) { 2497 GGML_ASSERT(tensor); 2498 GGML_ASSERT(tensor->buffer == NULL); 2499 GGML_ASSERT(tensor->view_src != NULL); 2500 GGML_ASSERT(tensor->view_src->buffer != NULL); 2501 GGML_ASSERT(tensor->view_src->data != NULL); 2502 2503 tensor->buffer = tensor->view_src->buffer; 2504 tensor->data = (char *)tensor->view_src->data + tensor->view_offs; 2505 return ggml_backend_buffer_init_tensor(tensor->buffer, tensor); 2506 } 2507 2508 enum ggml_status ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr) { 2509 GGML_ASSERT(tensor); 2510 GGML_ASSERT(tensor->buffer == NULL); 2511 GGML_ASSERT(tensor->data == NULL); 2512 GGML_ASSERT(tensor->view_src == NULL); 2513 GGML_ASSERT(addr >= ggml_backend_buffer_get_base(buffer)); 2514 GGML_ASSERT(ggml_backend_buffer_is_meta(buffer) || 2515 (char *) addr + ggml_backend_buffer_get_alloc_size(buffer, tensor) <= 2516 (char *) ggml_backend_buffer_get_base(buffer) + ggml_backend_buffer_get_size(buffer)); 2517 2518 tensor->buffer = buffer; 2519 tensor->data = addr; 2520 return ggml_backend_buffer_init_tensor(buffer, tensor); 2521 } 2522 2523 static struct ggml_tensor * graph_copy_dup_tensor(struct ggml_hash_set hash_set, struct ggml_tensor ** node_copies, 2524 struct ggml_context * ctx_allocated, struct ggml_context * ctx_unallocated, struct ggml_tensor * src) { 2525 2526 GGML_ASSERT(src != NULL); 2527 GGML_ASSERT(src->data && "graph must be allocated"); 2528 2529 size_t id = ggml_hash_insert(&hash_set, src); 2530 if (id == GGML_HASHSET_ALREADY_EXISTS) { 2531 return node_copies[ggml_hash_find(&hash_set, src)]; 2532 } 2533 2534 struct ggml_tensor * dst = ggml_dup_tensor_layout(src->data && !src->view_src ? ctx_allocated : ctx_unallocated, src); 2535 if (src->view_src != NULL) { 2536 dst->view_src = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, src->view_src); 2537 dst->view_offs = src->view_offs; 2538 } 2539 dst->op = src->op; 2540 dst->flags = src->flags; 2541 memcpy(dst->op_params, src->op_params, sizeof(dst->op_params)); 2542 ggml_set_name(dst, src->name); 2543 2544 // copy src 2545 for (int i = 0; i < GGML_MAX_SRC; i++) { 2546 struct ggml_tensor * s = src->src[i]; 2547 if (s == NULL) { 2548 continue; 2549 } 2550 dst->src[i] = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, s); 2551 } 2552 2553 node_copies[id] = dst; 2554 return dst; 2555 } 2556 2557 static void graph_copy_init_tensor(struct ggml_hash_set * hash_set, struct ggml_tensor ** node_copies, bool * node_init, struct ggml_tensor * src) { 2558 size_t id = ggml_hash_find(hash_set, src); 2559 if (node_init[id]) { 2560 return; 2561 } 2562 node_init[id] = true; 2563 2564 struct ggml_tensor * dst = node_copies[id]; 2565 if (dst->view_src != NULL) { 2566 graph_copy_init_tensor(hash_set, node_copies, node_init, src->view_src); 2567 enum ggml_status status = ggml_backend_view_init(dst); 2568 GGML_ASSERT(status == GGML_STATUS_SUCCESS); 2569 } 2570 else { 2571 ggml_backend_tensor_copy(src, dst); 2572 } 2573 2574 // init src 2575 for (int i = 0; i < GGML_MAX_SRC; i++) { 2576 struct ggml_tensor * s = src->src[i]; 2577 if (s == NULL) { 2578 continue; 2579 } 2580 graph_copy_init_tensor(hash_set, node_copies, node_init, s); 2581 } 2582 } 2583 2584 struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph) { 2585 GGML_ASSERT(graph); 2586 struct ggml_hash_set hash_set = ggml_hash_set_new(graph->visited_hash_set.size); 2587 struct ggml_tensor ** node_copies = (ggml_tensor **) calloc(hash_set.size, sizeof(node_copies[0])); // NOLINT 2588 bool * node_init = (bool *) calloc(hash_set.size, sizeof(node_init[0])); 2589 2590 struct ggml_init_params params = { 2591 /* .mem_size = */ ggml_tensor_overhead()*hash_set.size + ggml_graph_overhead_custom(graph->size, false), 2592 /* .mem_buffer = */ NULL, 2593 /* .no_alloc = */ true 2594 }; 2595 2596 struct ggml_context * ctx_allocated = ggml_init(params); 2597 struct ggml_context * ctx_unallocated = ggml_init(params); 2598 2599 if (ctx_allocated == NULL || ctx_unallocated == NULL) { 2600 GGML_LOG_ERROR("%s: failed to allocate context for graph copy\n", __func__); 2601 ggml_hash_set_free(&hash_set); 2602 free(node_copies); 2603 free(node_init); 2604 ggml_free(ctx_allocated); 2605 ggml_free(ctx_unallocated); 2606 return { 2607 /* .buffer = */ NULL, 2608 /* .ctx_allocated = */ NULL, 2609 /* .ctx_unallocated = */ NULL, 2610 /* .graph = */ NULL, 2611 }; 2612 } 2613 2614 // dup nodes 2615 for (int i = 0; i < graph->n_nodes; i++) { 2616 struct ggml_tensor * node = graph->nodes[i]; 2617 graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, node); 2618 } 2619 2620 // allocate nodes 2621 ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx_allocated, backend); 2622 if (buffer == NULL) { 2623 GGML_LOG_ERROR("%s: failed to allocate buffer for graph copy\n", __func__); 2624 ggml_hash_set_free(&hash_set); 2625 free(node_copies); 2626 free(node_init); 2627 ggml_free(ctx_allocated); 2628 ggml_free(ctx_unallocated); 2629 return { 2630 /* .buffer = */ NULL, 2631 /* .ctx_allocated = */ NULL, 2632 /* .ctx_unallocated = */ NULL, 2633 /* .graph = */ NULL, 2634 }; 2635 } 2636 2637 //printf("copy buffer size: %zu MB\n", ggml_backend_buffer_get_size(buffer) / 1024 / 1024); 2638 2639 // copy data and init views 2640 for (int i = 0; i < graph->n_nodes; i++) { 2641 struct ggml_tensor * node = graph->nodes[i]; 2642 graph_copy_init_tensor(&hash_set, node_copies, node_init, node); 2643 } 2644 2645 // build graph copy 2646 struct ggml_cgraph * graph_copy = ggml_new_graph_custom(ctx_allocated, graph->size, false); 2647 for (int i = 0; i < graph->n_nodes; i++) { 2648 struct ggml_tensor * node = graph->nodes[i]; 2649 struct ggml_tensor * node_copy = node_copies[ggml_hash_find(&hash_set, node)]; 2650 graph_copy->nodes[i] = node_copy; 2651 } 2652 graph_copy->n_nodes = graph->n_nodes; 2653 2654 ggml_hash_set_free(&hash_set); 2655 free(node_copies); 2656 free(node_init); 2657 2658 return { 2659 /* .buffer = */ buffer, 2660 /* .ctx_allocated = */ ctx_allocated, 2661 /* .ctx_unallocated = */ ctx_unallocated, 2662 /* .graph = */ graph_copy, 2663 }; 2664 } 2665 2666 void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy) { 2667 ggml_backend_buffer_free(copy.buffer); 2668 ggml_free(copy.ctx_allocated); 2669 ggml_free(copy.ctx_unallocated); 2670 } 2671 2672 bool ggml_backend_compare_graph_backend(ggml_backend_t backend1, ggml_backend_t backend2, struct ggml_cgraph * graph, ggml_backend_eval_callback callback, void * user_data, struct ggml_tensor const * const * test_nodes, size_t num_test_nodes) { 2673 struct ggml_backend_graph_copy copy = ggml_backend_graph_copy(backend2, graph); 2674 if (copy.buffer == NULL) { 2675 return false; 2676 } 2677 2678 struct ggml_cgraph * g1 = graph; 2679 struct ggml_cgraph * g2 = copy.graph; 2680 2681 assert(g1->n_nodes == g2->n_nodes); 2682 2683 if (num_test_nodes != 0) { 2684 GGML_ASSERT(test_nodes); 2685 // Compute the whole graph and only test the output for specific tensors 2686 ggml_backend_graph_compute(backend1, g1); 2687 ggml_backend_graph_compute(backend2, g2); 2688 2689 bool verified = false; 2690 for (int i = 0; i < g1->n_nodes; i++) { 2691 for (size_t j = 0; j < num_test_nodes; ++j) { 2692 if (g1->nodes[i] == test_nodes[j]) { 2693 callback(i, g1->nodes[i], g2->nodes[i], user_data); 2694 verified = true; 2695 } 2696 } 2697 } 2698 GGML_ASSERT(verified); 2699 } else { 2700 for (int i = 0; i < g1->n_nodes; i++) { 2701 struct ggml_tensor * t1 = g1->nodes[i]; 2702 struct ggml_tensor * t2 = g2->nodes[i]; 2703 2704 assert(t1->op == t2->op && ggml_are_same_layout(t1, t2)); 2705 2706 struct ggml_cgraph g1v = ggml_graph_view(g1, i, i + 1); 2707 struct ggml_cgraph g2v = ggml_graph_view(g2, i, i + 1); 2708 2709 ggml_backend_graph_compute(backend1, &g1v); 2710 ggml_backend_graph_compute(backend2, &g2v); 2711 2712 if (ggml_is_view_op(t1->op)) { 2713 continue; 2714 } 2715 2716 // compare results, calculate rms etc 2717 if (!callback(i, t1, t2, user_data)) { 2718 break; 2719 } 2720 } 2721 } 2722 ggml_backend_graph_copy_free(copy); 2723 2724 return true; 2725 } 2726 2727 // CPU backend - buffer 2728 2729 static void * ggml_backend_cpu_buffer_get_base(ggml_backend_buffer_t buffer) { 2730 GGML_ASSERT(buffer); 2731 uintptr_t data = (uintptr_t)buffer->context; 2732 2733 // align the buffer 2734 if (data % TENSOR_ALIGNMENT != 0) { 2735 data = GGML_PAD(data, TENSOR_ALIGNMENT); 2736 } 2737 2738 return (void *)data; 2739 } 2740 2741 static void ggml_backend_cpu_buffer_free_buffer(ggml_backend_buffer_t buffer) { 2742 GGML_ASSERT(buffer); 2743 ggml_aligned_free(buffer->context, buffer->size); 2744 } 2745 2746 static void ggml_backend_cpu_buffer_memset_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) { 2747 GGML_ASSERT(tensor); 2748 memset((char *)tensor->data + offset, value, size); 2749 2750 GGML_UNUSED(buffer); 2751 } 2752 2753 static void ggml_backend_cpu_buffer_set_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) { 2754 GGML_ASSERT(tensor); 2755 memcpy((char *)tensor->data + offset, data, size); 2756 2757 GGML_UNUSED(buffer); 2758 } 2759 2760 static void ggml_backend_cpu_buffer_get_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) { 2761 GGML_ASSERT(tensor); 2762 memcpy(data, (const char *)tensor->data + offset, size); 2763 2764 GGML_UNUSED(buffer); 2765 } 2766 2767 static bool ggml_backend_cpu_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * src, struct ggml_tensor * dst) { 2768 GGML_ASSERT(src); 2769 if (ggml_backend_buffer_is_host(src->buffer)) { 2770 memcpy(dst->data, src->data, ggml_nbytes(src)); 2771 return true; 2772 } 2773 return false; 2774 2775 GGML_UNUSED(buffer); 2776 } 2777 2778 static void ggml_backend_cpu_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) { 2779 GGML_ASSERT(buffer); 2780 memset(buffer->context, value, buffer->size); 2781 } 2782 2783 static const struct ggml_backend_buffer_i ggml_backend_cpu_buffer_i = { 2784 /* .free_buffer = */ ggml_backend_cpu_buffer_free_buffer, 2785 /* .get_base = */ ggml_backend_cpu_buffer_get_base, 2786 /* .init_tensor = */ NULL, // no initialization required 2787 /* .memset_tensor = */ ggml_backend_cpu_buffer_memset_tensor, 2788 /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor, 2789 /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor, 2790 /* .set_tensor_2d = */ NULL, 2791 /* .get_tensor_2d = */ NULL, 2792 /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor, 2793 /* .clear = */ ggml_backend_cpu_buffer_clear, 2794 /* .reset = */ NULL, 2795 /* .set_tensor_n = */ NULL, 2796 /* .get_tensor_n = */ NULL, 2797 /* .cpy_tensor_n = */ NULL, 2798 }; 2799 2800 static const struct ggml_backend_buffer_i ggml_backend_cpu_buffer_from_ptr_i = { 2801 /* .free_buffer = */ NULL, // ptr is not owned by the buffer, so it does not need to be freed 2802 /* .get_base = */ ggml_backend_cpu_buffer_get_base, 2803 /* .init_tensor = */ NULL, // no initialization required 2804 /* .memset_tensor = */ ggml_backend_cpu_buffer_memset_tensor, 2805 /* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor, 2806 /* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor, 2807 /* .set_tensor_2d = */ NULL, 2808 /* .get_tensor_2d = */ NULL, 2809 /* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor, 2810 /* .clear = */ ggml_backend_cpu_buffer_clear, 2811 /* .reset = */ NULL, 2812 /* .set_tensor_n = */ NULL, 2813 /* .get_tensor_n = */ NULL, 2814 /* .cpy_tensor_n = */ NULL, 2815 }; 2816 2817 // CPU backend buffer type 2818 2819 // this buffer type is defined here to make it available to all backends 2820 2821 static const char * ggml_backend_cpu_buffer_type_get_name(ggml_backend_buffer_type_t buft) { 2822 return "CPU"; 2823 2824 GGML_UNUSED(buft); 2825 } 2826 2827 static ggml_backend_buffer_t ggml_backend_cpu_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) { 2828 void * data = ggml_aligned_malloc(size); 2829 2830 if (data == NULL) { 2831 GGML_LOG_ERROR("%s: failed to allocate buffer of size %zu\n", __func__, size); 2832 return NULL; 2833 } 2834 2835 return ggml_backend_buffer_init(buft, ggml_backend_cpu_buffer_i, data, size); 2836 } 2837 2838 static size_t ggml_backend_cpu_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) { 2839 return TENSOR_ALIGNMENT; 2840 2841 GGML_UNUSED(buft); 2842 } 2843 2844 static bool ggml_backend_cpu_buffer_type_is_host(ggml_backend_buffer_type_t buft) { 2845 return true; 2846 2847 GGML_UNUSED(buft); 2848 } 2849 2850 ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void) { 2851 static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = { 2852 /* .iface = */ { 2853 /* .get_name = */ ggml_backend_cpu_buffer_type_get_name, 2854 /* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer, 2855 /* .alloc_buffer_n = */ NULL, 2856 /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment, 2857 /* .get_max_size = */ NULL, // defaults to SIZE_MAX 2858 /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes 2859 /* .get_alloc_size_n = */ NULL, 2860 /* .is_host = */ ggml_backend_cpu_buffer_type_is_host, 2861 }, 2862 /* .device = */ NULL, // FIXME ggml_backend_reg_dev_get(ggml_backend_cpu_reg(), 0), 2863 /* .context = */ NULL, 2864 }; 2865 2866 return &ggml_backend_cpu_buffer_type; 2867 } 2868 2869 static const char * ggml_backend_cpu_buffer_from_ptr_type_get_name(ggml_backend_buffer_type_t buft) { 2870 return "CPU_Mapped"; 2871 2872 GGML_UNUSED(buft); 2873 } 2874 2875 static ggml_backend_buffer_type_t ggml_backend_cpu_buffer_from_ptr_type(void) { 2876 static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = { 2877 /* .iface = */ { 2878 /* .get_name = */ ggml_backend_cpu_buffer_from_ptr_type_get_name, 2879 /* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer, 2880 /* .alloc_buffer_n = */ NULL, 2881 /* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment, 2882 /* .get_max_size = */ NULL, // defaults to SIZE_MAX 2883 /* .get_alloc_size = */ NULL, // defaults to ggml_nbytes 2884 /* .get_alloc_size_n = */ NULL, 2885 /* .is_host = */ ggml_backend_cpu_buffer_type_is_host, 2886 }, 2887 /* .device = */ NULL, // FIXME ggml_backend_reg_dev_get(ggml_backend_cpu_reg(), 0), 2888 /* .context = */ NULL, 2889 }; 2890 2891 return &ggml_backend_cpu_buffer_type; 2892 } 2893 2894 ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size) { 2895 GGML_ASSERT((uintptr_t)ptr % TENSOR_ALIGNMENT == 0 && "buffer pointer must be aligned"); 2896 return ggml_backend_buffer_init(ggml_backend_cpu_buffer_from_ptr_type(), ggml_backend_cpu_buffer_from_ptr_i, ptr, size); 2897 }