Library side of the on-demand VRAM time-sharing: weights, KV/recurrent state, MoE cache, scheduler and backend scratch (ggml_backend_free_scratch); guards for released buffers and cold teardown. This commit holds the src/, ggml/ and include/ parts of the commits below; their tools/mtmd and tools/server parts are in the next two commits. Squashed from 11 fork commits (original subjects and messages below). ---- server: on-demand VRAM sharing to time-share one GPU between models (wascb489f336) Add release/restore of a model's GPU weight buffers (keeping a host shadow and the KV cache) so several always-loaded llama-server processes can time-share a single GPU without reloading or losing the prompt cache. - llama-model: release_device_weights()/restore_device_weights() capture a compact host shadow (stable iteration order, view-skipping) and free then realloc the device weight buffers; weights_resident() query. - llama-context: release_device()/restore_device() wrappers; decode() auto- restores; public C API llama_context_release_device/restore_device. - server: LLAMA_SLEEP_VRAM_ONLY makes idle-sleep release only the VRAM weights (not a full unload/reload). A cross-process flock token in LLAMA_VRAM_ARENA enforces "resident iff holds token"; an inotify doorbell forces the holder to release on contention. The warden thread only touches the task queue, so releases run on the loop thread and never race a decode. Validated on RX 580 (Vulkan): two models share 8GB, never both resident, correct output under contention, KV cache preserved (no re-prefill). ---- server: optionally evict the KV cache too (Phase 2 of VRAM sharing) (was3b410b905) Extend on-demand device residency to the KV cache so that when a model's KV plus another model would not fit in VRAM, the KV can also be evicted to a host shadow (D2H on release, H2D on restore) instead of only the weights. - llama_memory_i: add release_device_buffers()/restore_device_buffers() (default no-op). Implemented in llama_kv_cache (D2H shadow of the live ctxs_bufs, freed and reallocated like the weights); llama_memory_hybrid and llama_kv_cache_iswa delegate to their child caches. - llama_context::release_device(evict_kv): also evict the memory's device buffers when requested; restore_device() rebuilds them. Public API llama_context_release_device gains an evict_kv flag. - server: LLAMA_SLEEP_EVICT_KV=1 enables it. Off by default (weights-only), since the KV shadow adds a D2H/H2D copy of the live cache each cycle. Validated on RX 580 (Vulkan), 4B @ 32k ctx: weights-only cold VRAM 1750 MB (KV stays); weights+KV cold VRAM 726 MB (KV freed, ~1 GB reclaimed). KV survives the round-trip: prompt cache reused after the cycle (prompt_n 4 vs 42), correct output. ---- llama: guard buffer iteration against released device buffers (was9119ec6e8) release_device_weights()/release_device_buffers() leave a null buffer in ctxs_bufs while the device memory is released for on-demand VRAM sharing. The memory-breakdown / total_size / clear paths iterated these and called ggml_backend_buffer_get_size()/get_type()/clear() on the null buffer, tripping GGML_ASSERT(buffer) and aborting on shutdown of a cold model. Skip null buffers in llama_model::memory_breakdown and llama_kv_cache::{memory_breakdown, total_size,clear}. ---- server: also free the compute-graph scheduler on KV eviction (was298da30d9) Under LLAMA_SLEEP_EVICT_KV a cold model still held the scheduler's worst-case compute buffer (hundreds of MiB, e.g. ~700 MiB for gemma-26B) plus the resident experts. release_device(evict_kv) now also frees the sched (sched.reset() + sched_need_reserve), and restore_device() rebuilds it via sched_reserve(), so a fully-evicted model holds essentially no VRAM (gemma cold: 7147 -> 51 MiB). Trades a heavier re-warm (weights+KV H2D + sched reserve) for the freed VRAM; weights-only mode is unchanged (fast switch, keeps KV+compute). ---- llama: evict recurrent/SSM state on device release (wasb4a09407a) The recurrent (SSM/conv) state of hybrid models (e.g. Qwen3.5) was left resident when a model's device buffers were released for on-demand VRAM sharing - llama_memory_recurrent::release_device_buffers() was a no-op default. Implement it (and restore_device_buffers) with the same capture-host-shadow / free / reallocate pattern as llama_kv_cache, so llama_memory_hybrid now evicts both its attention KV and its recurrent state. The state is read-write, so its shadow is recaptured on every release. ---- ggml: add ggml_backend_free_scratch to drop Vulkan compute prealloc (was7992a094d) Add an optional backend interface method free_scratch (with a public ggml_backend_free_scratch wrapper) that frees transient/scratch device memory a backend holds outside of any allocated buffer, keeping the backend usable - the scratch is reallocated lazily on the next compute. Implement it for the Vulkan backend (ggml_backend_vk_free_scratch): free the prealloc_x/y/split_k/add_rms_partials and sync_staging device buffers and reset their sizes, so an idle/cold model does not hold the vision or matmul compute preallocations in VRAM. All other backends leave the hook null (no-op). ---- llama: free backend compute scratch on cold; guard memory_breakdown (was392787dee) On device release with KV eviction, also call ggml_backend_free_scratch() on each backend so a cold model drops its Vulkan compute preallocations (reallocated lazily on the next compute via restore). Also guard llama_context::memory_breakdown() against a freed scheduler: evict_kv release resets sched to null, so a cold model that is then torn down (e.g. terminated by the process manager) hit GGML_ASSERT(sched) in ggml_backend_sched_get_buffer_type. Skip the compute-buffer accounting when sched is null. ---- llama: skip the compute-buffer size check when the context is cold (was9df58a961) release_device(evict_kv) drops the scheduler, so a context evicted by the VRAM arbiter and then destroyed reaches the destructor with a null sched. The upstream "compute buffer size matches expectation" loop calls ggml_backend_sched_get_buffer_size() unconditionally, whose GGML_ASSERT(sched) then aborts: the server exits 134 instead of 0 on every shutdown taken while cold, which under llama-swap makes an ordinary stop look like a crashed child and leaves a ggml backtrace in the log each time. It also skipped the rest of the destructor, so the cold teardown path had never actually run to completion. Guard at the call site rather than relaxing the assert - the assert is right, and every other caller reserves the scheduler first. Same shape as the null guards in synchronize(), memory_breakdown() and the released-buffer iteration. The loop is a diagnostic size comparison, already reported by sched_reserve() at load, so skipping it when cold loses nothing. ---- llama: release/restore the MoE cache with the device weights (was1ee9747e1) The MoE cache (--moe-cache-mib, #29887) keeps the most recently used host experts in device banks. The on-demand VRAM path (release_device / restore_device, used by the server VRAM arbiter and the on-demand mmproj path) did not know about it, so its banks were never freed on handoff. Restoring them by reallocation alone would also be wrong: the banks come back zeroed while the slot maps still mark experts as cached, so the model would silently read zero weights. Free the banks on release and empty the cache instead of shadowing it: re-init every LRU, re-point its slot-map pointers at the host slot maps and clear those to -1. The banks are reallocated (which also re-inits their views) and cleared on restore, before the scheduler is rebuilt, and the cache refills from the host experts as before. Release runs in both modes, weights-only and evict_kv. device_resident() now covers the cache too, for the early returns in release/restore, the auto-restore in decode() and llama_context_weights_resident(). ---- server: release the GPU token promptly on shutdown (was83cc51c9d) Two ways a shutting-down server kept the VRAM arbiter's token, stalling every other model: - SIGTERM with a request in flight: terminate() stopped only the task queue. The HTTP handler kept waiting for results the loop would never send, the main thread blocked joining it, and the token was released only in the destructor after that join - i.e. never, until the client went away. Terminate the result queue too (readers now get "server is shutting down": a 503, or an SSE error event), and let wait_until_no_sleep give up once stopping. - SIGTERM while waiting for the token: the loop thread sat in a blocking flock inside the wake callback, holding mutex_tasks, so terminate() waited for the current holder to finish and then for a pointless restore of our weights. Poll the lock non-blocking and abort the wait on shutdown; the aborted wake stays cold, skips the restore, and the loop exits before update_slots. Also release the token right after start_loop() returns rather than in the destructor, and only after the device buffers are actually freed: the old order unlocked before destroy(), so the next model could start uploading into VRAM that was still occupied. Freeing at exit uses a new llama_context_discard_device(), which drops weights, KV, MoE cache and scratch without capturing host shadows first. Off production: SIGTERM mid-generation or mid-wait now exits in ~0.2 s with exit 0 and frees the token within 5-70 ms (previously never / after the holder's whole generation). Handoff latency and greedy output are unchanged. ---- llama: do not release CPU extra buffers (CPU_REPACK) on device release (was724a5d637) A model with weights on the CPU device (-dev none / -ngl 0) segfaulted in llama_model::release_device_weights() the first time the VRAM arbiter put it to sleep: CPU_REPACK buffers are not host buffers, so load_tensors marked them releasable, and capturing the shadow called their NULL get_tensor. Reproduced with the production build2fc9f9c35(Qwen3.5-0.8B, -dev none -ngl 0, LLAMA_SLEEP_VRAM_ONLY=1 LLAMA_SLEEP_EVICT_KV=1, force a yield with a waiter on want.lock): exit 139 at the release, before any SIGTERM. The faulting call (rip 0) returned into release_device_weights. Only buffers on a non-CPU device are releasable now. These buffers are in RAM already, so there is nothing to free. Production is not affected: every arbiter model there has its weights on the GPU, and a releasable CPU_REPACK buffer would have crashed it. Found by the --diskcache check, which runs its arbiter cases CPU only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PZz44SLQvTXMyWGio6t9DZ
3005 lines
115 KiB
C++
3005 lines
115 KiB
C++
// Note: porting this file to C++ is a work in progress
|
|
|
|
#ifdef _WIN32
|
|
#define WIN32_LEAN_AND_MEAN
|
|
#ifndef NOMINMAX
|
|
# define NOMINMAX
|
|
#endif
|
|
#include <windows.h>
|
|
#endif
|
|
|
|
#include "ggml-backend.h"
|
|
#include "ggml-backend-impl.h"
|
|
#include "ggml-alloc.h"
|
|
#include "ggml-impl.h"
|
|
|
|
#include <assert.h>
|
|
#include <limits.h>
|
|
#include <stdarg.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <algorithm>
|
|
#include <unordered_map>
|
|
#include <vector>
|
|
|
|
#ifdef __APPLE__
|
|
#include <sys/types.h>
|
|
#include <sys/sysctl.h>
|
|
#endif
|
|
|
|
|
|
// backend buffer type
|
|
|
|
const char * ggml_backend_buft_name(ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(buft);
|
|
return buft->iface.get_name(buft);
|
|
}
|
|
|
|
ggml_backend_buffer_t ggml_backend_buft_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
|
|
GGML_ASSERT(buft);
|
|
if (size == 0) {
|
|
// return a dummy buffer for zero-sized allocations
|
|
return ggml_backend_buffer_init(buft, {}, NULL, 0);
|
|
}
|
|
return buft->iface.alloc_buffer(buft, size);
|
|
}
|
|
|
|
// shared planning logic for allocating a list of tensors into one or more buffers of the given type
|
|
struct ggml_backend_buft_alloc_buffer_n_plan_item {
|
|
size_t size; // total bytes for this buffer
|
|
int first; // first tensor index (inclusive)
|
|
int last; // last tensor index (exclusive)
|
|
};
|
|
|
|
using ggml_backend_buft_alloc_buffer_n_plan_t = std::vector<ggml_backend_buft_alloc_buffer_n_plan_item>;
|
|
|
|
static ggml_backend_buft_alloc_buffer_n_plan_t ggml_backend_buft_alloc_buffer_n_plan(
|
|
ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
|
|
ggml_backend_buft_alloc_buffer_n_plan_t plan;
|
|
|
|
const size_t alignment = ggml_backend_buft_get_alignment(buft);
|
|
const size_t max_size = ggml_backend_buft_get_max_size(buft);
|
|
|
|
size_t cur_buf_size = 0;
|
|
int first = 0;
|
|
|
|
for (int i = 0; i < n_tensors; i++) {
|
|
size_t this_size = 0;
|
|
struct ggml_tensor * t = tensors[i];
|
|
if (t->data == NULL && t->view_src == NULL) {
|
|
this_size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, t), alignment);
|
|
}
|
|
|
|
// flush the current buffer if adding this tensor would exceed max_size
|
|
if (cur_buf_size > 0 && (cur_buf_size + this_size) > max_size) {
|
|
plan.push_back({ cur_buf_size, first, i });
|
|
cur_buf_size = this_size;
|
|
first = i;
|
|
} else {
|
|
cur_buf_size += this_size;
|
|
}
|
|
}
|
|
|
|
if (cur_buf_size > 0) {
|
|
plan.push_back({ cur_buf_size, first, n_tensors });
|
|
}
|
|
|
|
return plan;
|
|
}
|
|
|
|
// default implementation of alloc_buffer_n
|
|
// allocates tensors from a list into one or more buffers of the given type
|
|
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) {
|
|
const ggml_backend_buft_alloc_buffer_n_plan_t plan = ggml_backend_buft_alloc_buffer_n_plan(buft, tensors, n_tensors);
|
|
|
|
std::vector<ggml_backend_buffer_t> buffers;
|
|
buffers.reserve(plan.size());
|
|
|
|
for (const ggml_backend_buft_alloc_buffer_n_plan_item & item : plan) {
|
|
ggml_backend_buffer_t buffer = ggml_backend_buft_alloc_buffer(buft, item.size);
|
|
if (buffer == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate %s buffer of size %zu\n", __func__, ggml_backend_buft_name(buft), item.size);
|
|
for (ggml_backend_buffer_t b : buffers) {
|
|
ggml_backend_buffer_free(b);
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
struct ggml_tallocr tallocr = ggml_tallocr_new(buffer);
|
|
|
|
// allocate tensors in the current buffer
|
|
struct ggml_tensor * t_failed = NULL;
|
|
for (int j = item.first; j < item.last; j++) {
|
|
struct ggml_tensor * t = tensors[j];
|
|
if (t->data == NULL) {
|
|
if (t->view_src == NULL) {
|
|
if (ggml_tallocr_alloc(&tallocr, t) != GGML_STATUS_SUCCESS) {
|
|
t_failed = t;
|
|
break;
|
|
}
|
|
} else if (t->buffer == NULL) {
|
|
if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) {
|
|
t_failed = t;
|
|
break;
|
|
}
|
|
}
|
|
} else {
|
|
if (t->view_src != NULL && t->buffer == NULL) {
|
|
// view of a pre-allocated tensor
|
|
if (ggml_backend_view_init(t) != GGML_STATUS_SUCCESS) {
|
|
t_failed = t;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (t_failed != NULL) {
|
|
GGML_LOG_ERROR("%s: failed to initialize tensor %s\n", __func__, t_failed->name);
|
|
for (ggml_backend_buffer_t b : buffers) {
|
|
ggml_backend_buffer_free(b);
|
|
}
|
|
ggml_backend_buffer_free(buffer);
|
|
return NULL;
|
|
}
|
|
|
|
buffers.push_back(buffer);
|
|
}
|
|
|
|
if (buffers.empty()) {
|
|
return NULL;
|
|
}
|
|
|
|
if (buffers.size() == 1) {
|
|
return buffers[0];
|
|
}
|
|
|
|
return ggml_backend_multi_buffer_alloc_buffer(buffers.data(), buffers.size());
|
|
}
|
|
|
|
// default implementation of get_alloc_size_n
|
|
// returns the total size that alloc_buffer_n_default would allocate for the given tensors
|
|
static size_t ggml_backend_buft_get_alloc_size_n_default(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
|
|
const ggml_backend_buft_alloc_buffer_n_plan_t plan = ggml_backend_buft_alloc_buffer_n_plan(buft, tensors, n_tensors);
|
|
|
|
size_t total = 0;
|
|
for (const ggml_backend_buft_alloc_buffer_n_plan_item & item : plan) {
|
|
total += item.size;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
ggml_backend_buffer_t ggml_backend_buft_alloc_buffer_n(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
|
|
GGML_ASSERT(buft);
|
|
if (buft->iface.alloc_buffer_n) {
|
|
return buft->iface.alloc_buffer_n(buft, tensors, n_tensors);
|
|
}
|
|
return ggml_backend_buft_alloc_buffer_n_default(buft, tensors, n_tensors);
|
|
}
|
|
|
|
size_t ggml_backend_buft_get_alignment(ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(buft);
|
|
return buft->iface.get_alignment(buft);
|
|
}
|
|
|
|
size_t ggml_backend_buft_get_max_size(ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(buft);
|
|
// get_max_size is optional, defaults to SIZE_MAX
|
|
if (buft->iface.get_max_size) {
|
|
return buft->iface.get_max_size(buft);
|
|
}
|
|
return SIZE_MAX;
|
|
}
|
|
|
|
size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * tensor) {
|
|
GGML_ASSERT(buft);
|
|
// get_alloc_size is optional, defaults to ggml_nbytes
|
|
if (buft->iface.get_alloc_size) {
|
|
size_t size = buft->iface.get_alloc_size(buft, tensor);
|
|
assert(size >= ggml_nbytes(tensor));
|
|
|
|
// [TAG_ALLOC_SIZE_EXPAND]
|
|
// if you hit this assert, update ggml_backend_op_alloc_size_may_expand() accordingly
|
|
GGML_ASSERT(size <= ggml_nbytes(tensor) ||
|
|
ggml_op_is_empty(tensor->op) ||
|
|
ggml_is_quantized(tensor->type) || // [TAG_ALLOC_SIZE_EXPAND]
|
|
ggml_op_alloc_size_may_expand(tensor->op));
|
|
|
|
return size;
|
|
}
|
|
return ggml_nbytes(tensor);
|
|
}
|
|
|
|
size_t ggml_backend_buft_get_alloc_size_n(ggml_backend_buffer_type_t buft, struct ggml_tensor ** tensors, int n_tensors) {
|
|
GGML_ASSERT(buft);
|
|
if (buft->iface.get_alloc_size_n) {
|
|
return buft->iface.get_alloc_size_n(buft, tensors, n_tensors);
|
|
}
|
|
return ggml_backend_buft_get_alloc_size_n_default(buft, tensors, n_tensors);
|
|
}
|
|
|
|
bool ggml_backend_buft_is_host(ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(buft);
|
|
if (buft->iface.is_host) {
|
|
return buft->iface.is_host(buft);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
ggml_backend_dev_t ggml_backend_buft_get_device(ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(buft);
|
|
return buft->device;
|
|
}
|
|
|
|
// backend buffer
|
|
|
|
ggml_backend_buffer_t ggml_backend_buffer_init(
|
|
ggml_backend_buffer_type_t buft,
|
|
struct ggml_backend_buffer_i iface,
|
|
void * context,
|
|
size_t size) {
|
|
ggml_backend_buffer_t buffer = new ggml_backend_buffer {
|
|
/* .interface = */ iface,
|
|
/* .buft = */ buft,
|
|
/* .context = */ context,
|
|
/* .size = */ size,
|
|
/* .usage = */ GGML_BACKEND_BUFFER_USAGE_ANY
|
|
};
|
|
|
|
return buffer;
|
|
}
|
|
|
|
const char * ggml_backend_buffer_name(ggml_backend_buffer_t buffer) {
|
|
return ggml_backend_buft_name(ggml_backend_buffer_get_type(buffer));
|
|
}
|
|
|
|
void ggml_backend_buffer_free(ggml_backend_buffer_t buffer) {
|
|
if (buffer == NULL) {
|
|
return;
|
|
}
|
|
|
|
if (buffer->iface.free_buffer != NULL) {
|
|
buffer->iface.free_buffer(buffer);
|
|
}
|
|
delete buffer;
|
|
}
|
|
|
|
size_t ggml_backend_buffer_get_size(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
return buffer->size;
|
|
}
|
|
|
|
void * ggml_backend_buffer_get_base(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
// get_base is optional if the buffer is zero-sized
|
|
if (!ggml_backend_buffer_is_meta(buffer) && buffer->size == 0) {
|
|
return NULL;
|
|
}
|
|
|
|
// FIXME JG: a multi_buffer has a non-zero size, according to the above comment get_base is not optional,
|
|
// I don't know whether the above comment is correct
|
|
if (!buffer->iface.get_base) {
|
|
return NULL;
|
|
}
|
|
|
|
void * base = buffer->iface.get_base(buffer);
|
|
|
|
GGML_ASSERT(base != NULL && "backend buffer base cannot be NULL");
|
|
|
|
return base;
|
|
}
|
|
|
|
enum ggml_status ggml_backend_buffer_init_tensor(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor) {
|
|
GGML_ASSERT(buffer);
|
|
// init_tensor is optional
|
|
if (buffer->iface.init_tensor) {
|
|
return buffer->iface.init_tensor(buffer, tensor);
|
|
}
|
|
return GGML_STATUS_SUCCESS;
|
|
}
|
|
|
|
void ggml_backend_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
|
|
GGML_ASSERT(buffer);
|
|
// clear is optional if the buffer is zero-sized
|
|
if (buffer->size == 0) {
|
|
return;
|
|
}
|
|
|
|
buffer->iface.clear(buffer, value);
|
|
}
|
|
|
|
size_t ggml_backend_buffer_get_alignment(ggml_backend_buffer_t buffer) {
|
|
return ggml_backend_buft_get_alignment(ggml_backend_buffer_get_type(buffer));
|
|
}
|
|
|
|
size_t ggml_backend_buffer_get_max_size(ggml_backend_buffer_t buffer) {
|
|
return ggml_backend_buft_get_max_size(ggml_backend_buffer_get_type(buffer));
|
|
}
|
|
|
|
size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor) {
|
|
return ggml_backend_buft_get_alloc_size(ggml_backend_buffer_get_type(buffer), tensor);
|
|
}
|
|
|
|
bool ggml_backend_buffer_is_host(ggml_backend_buffer_t buffer) {
|
|
return ggml_backend_buft_is_host(ggml_backend_buffer_get_type(buffer));
|
|
}
|
|
|
|
void ggml_backend_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) {
|
|
GGML_ASSERT(buffer);
|
|
buffer->usage = usage;
|
|
|
|
// FIXME: add a generic callback to the buffer interface
|
|
if (ggml_backend_buffer_is_multi_buffer(buffer)) {
|
|
ggml_backend_multi_buffer_set_usage(buffer, usage);
|
|
} else if (ggml_backend_buffer_is_meta(buffer)) {
|
|
ggml_backend_meta_buffer_set_usage(buffer, usage);
|
|
}
|
|
}
|
|
|
|
enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
return buffer->usage;
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_buffer_get_type(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
return buffer->buft;
|
|
}
|
|
|
|
void ggml_backend_buffer_reset(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
if (buffer->iface.reset) {
|
|
buffer->iface.reset(buffer);
|
|
}
|
|
}
|
|
|
|
bool ggml_backend_buffer_copy_tensor(const struct ggml_tensor * src, struct ggml_tensor * dst) {
|
|
ggml_backend_buffer_t dst_buf = dst->view_src ? dst->view_src->buffer : dst->buffer;
|
|
if (dst_buf->iface.cpy_tensor) {
|
|
return dst_buf->iface.cpy_tensor(dst_buf, src, dst);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// backend
|
|
|
|
ggml_guid_t ggml_backend_guid(ggml_backend_t backend) {
|
|
if (backend == NULL) {
|
|
return NULL;
|
|
}
|
|
return backend->guid;
|
|
}
|
|
|
|
const char * ggml_backend_name(ggml_backend_t backend) {
|
|
if (backend == NULL) {
|
|
return "NULL";
|
|
}
|
|
return backend->iface.get_name(backend);
|
|
}
|
|
|
|
void ggml_backend_free(ggml_backend_t backend) {
|
|
if (backend == NULL) {
|
|
return;
|
|
}
|
|
|
|
backend->iface.free(backend);
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend) {
|
|
GGML_ASSERT(backend);
|
|
return ggml_backend_dev_buffer_type(backend->device);
|
|
}
|
|
|
|
ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size) {
|
|
return ggml_backend_buft_alloc_buffer(ggml_backend_get_default_buffer_type(backend), size);
|
|
}
|
|
|
|
size_t ggml_backend_get_alignment(ggml_backend_t backend) {
|
|
return ggml_backend_buft_get_alignment(ggml_backend_get_default_buffer_type(backend));
|
|
}
|
|
|
|
size_t ggml_backend_get_max_size(ggml_backend_t backend) {
|
|
return ggml_backend_buft_get_max_size(ggml_backend_get_default_buffer_type(backend));
|
|
}
|
|
|
|
template <typename cb_get_buffer>
|
|
static void ggml_backend_tensor_buft_groups(size_t n_tensors, cb_get_buffer && get_buffer, std::vector<std::vector<size_t>> & groups) {
|
|
std::unordered_map<ggml_backend_buffer_type_t, size_t> buft_idx;
|
|
groups.clear();
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
ggml_backend_buffer_t buf = get_buffer(i);
|
|
auto it = buft_idx.find(buf->buft);
|
|
if (it == buft_idx.end()) {
|
|
buft_idx[buf->buft] = groups.size();
|
|
groups.emplace_back();
|
|
}
|
|
groups[buft_idx[buf->buft]].push_back(i);
|
|
}
|
|
}
|
|
|
|
static bool ggml_backend_tensor_batch_is_2d(
|
|
const struct ggml_tensor * const * tensors,
|
|
const size_t * offsets,
|
|
const size_t * sizes,
|
|
const size_t * data_offsets,
|
|
size_t n_tensors,
|
|
size_t * base_offset,
|
|
size_t * size,
|
|
size_t * stride_tensor,
|
|
size_t * stride_data) {
|
|
if (n_tensors <= 1) {
|
|
return false;
|
|
}
|
|
|
|
const struct ggml_tensor * tensor = tensors[0];
|
|
const size_t size0 = sizes[0];
|
|
|
|
if (size0 == 0 || offsets[1] < offsets[0] || data_offsets[1] < data_offsets[0]) {
|
|
return false;
|
|
}
|
|
|
|
const size_t stride_tensor0 = offsets[1] - offsets[0];
|
|
const size_t stride_data0 = data_offsets[1] - data_offsets[0];
|
|
|
|
for (size_t i = 1; i < n_tensors; i++) {
|
|
if (tensors[i] != tensor || sizes[i] != size0) {
|
|
return false;
|
|
}
|
|
if (offsets[i] != offsets[0] + i*stride_tensor0 || data_offsets[i] != data_offsets[0] + i*stride_data0) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
*base_offset = offsets[0];
|
|
*size = size0;
|
|
*stride_tensor = stride_tensor0;
|
|
*stride_data = stride_data0;
|
|
|
|
return true;
|
|
}
|
|
|
|
void ggml_backend_tensor_set_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
|
|
|
if (backend->iface.set_tensor_async == NULL) {
|
|
ggml_backend_synchronize(backend);
|
|
ggml_backend_tensor_set(tensor, data, offset, size);
|
|
} else {
|
|
backend->iface.set_tensor_async(backend, tensor, data, offset, size);
|
|
}
|
|
}
|
|
|
|
void ggml_backend_tensor_get_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
|
|
|
|
if (backend->iface.get_tensor_async == NULL) {
|
|
ggml_backend_synchronize(backend);
|
|
ggml_backend_tensor_get(tensor, data, offset, size);
|
|
} else {
|
|
backend->iface.get_tensor_async(backend, tensor, data, offset, size);
|
|
}
|
|
}
|
|
|
|
void ggml_backend_tensor_set_2d_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size,
|
|
size_t n_copies, size_t stride_tensor, size_t stride_data) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
|
|
if (n_copies <= 1 || backend->iface.set_tensor_2d_async == NULL) {
|
|
for (size_t i = 0; i < n_copies; i++) {
|
|
ggml_backend_tensor_set_async(backend, tensor, (const char *) data + i*stride_data, offset + i*stride_tensor, size);
|
|
}
|
|
return;
|
|
}
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
|
backend->iface.set_tensor_2d_async(backend, tensor, data, offset, size, n_copies, stride_tensor, stride_data);
|
|
}
|
|
|
|
void ggml_backend_tensor_get_2d_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size,
|
|
size_t n_copies, size_t stride_tensor, size_t stride_data) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
|
|
if (n_copies <= 1 || backend->iface.get_tensor_2d_async == NULL) {
|
|
for (size_t i = 0; i < n_copies; i++) {
|
|
ggml_backend_tensor_get_async(backend, tensor, (char *) data + i*stride_data, offset + i*stride_tensor, size);
|
|
}
|
|
return;
|
|
}
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
|
|
backend->iface.get_tensor_2d_async(backend, tensor, data, offset, size, n_copies, stride_tensor, stride_data);
|
|
}
|
|
|
|
void ggml_backend_tensor_set(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size) {
|
|
GGML_ASSERT(tensor);
|
|
ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
|
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
|
|
|
buf->iface.set_tensor(buf, tensor, data, offset, size);
|
|
}
|
|
|
|
void ggml_backend_tensor_get(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size) {
|
|
GGML_ASSERT(tensor);
|
|
ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
|
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
|
|
|
|
buf->iface.get_tensor(buf, tensor, data, offset, size);
|
|
}
|
|
|
|
void ggml_backend_tensor_set_2d(struct ggml_tensor * tensor, const void * data, size_t offset, size_t size,
|
|
size_t n_copies, size_t stride_tensor, size_t stride_data) {
|
|
GGML_ASSERT(tensor);
|
|
ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
|
|
|
if (n_copies <= 1 || buf->iface.set_tensor_2d == NULL) {
|
|
for (size_t i = 0; i < n_copies; i++) {
|
|
ggml_backend_tensor_set(tensor, (const char *) data + i*stride_data, offset + i*stride_tensor, size);
|
|
}
|
|
return;
|
|
}
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
|
|
|
buf->iface.set_tensor_2d(buf, tensor, data, offset, size, n_copies, stride_tensor, stride_data);
|
|
}
|
|
|
|
void ggml_backend_tensor_get_2d(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size,
|
|
size_t n_copies, size_t stride_tensor, size_t stride_data) {
|
|
GGML_ASSERT(tensor);
|
|
ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
|
|
|
if (n_copies <= 1 || buf->iface.get_tensor_2d == NULL) {
|
|
for (size_t i = 0; i < n_copies; i++) {
|
|
ggml_backend_tensor_get(tensor, (char *) data + i*stride_data, offset + i*stride_tensor, size);
|
|
}
|
|
return;
|
|
}
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + (n_copies-1)*stride_tensor + size <= ggml_nbytes(tensor) && "tensor read out of bounds");
|
|
|
|
buf->iface.get_tensor_2d(buf, tensor, data, offset, size, n_copies, stride_tensor, stride_data);
|
|
}
|
|
|
|
void ggml_backend_tensor_set_n(struct ggml_tensor * const * tensors, const void * data,
|
|
const size_t * offsets, const size_t * sizes, const size_t * data_offsets, size_t n_tensors) {
|
|
if (n_tensors == 0) {
|
|
return;
|
|
}
|
|
|
|
std::vector<const void *> data_ptrs(n_tensors);
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
data_ptrs[i] = (const char *) data + data_offsets[i];
|
|
}
|
|
|
|
ggml_backend_buffer_t buf = NULL;
|
|
bool same_buft = true;
|
|
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
GGML_ASSERT(tensors[i] != NULL);
|
|
ggml_backend_buffer_t tensor_buf = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer;
|
|
GGML_ASSERT(tensor_buf != NULL && "tensor buffer not set");
|
|
GGML_ASSERT(tensors[i]->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offsets[i] + sizes[i] <= ggml_nbytes(tensors[i]) && "tensor write out of bounds");
|
|
|
|
if (buf == NULL) {
|
|
buf = tensor_buf;
|
|
} else if (buf->buft != tensor_buf->buft) {
|
|
same_buft = false;
|
|
}
|
|
}
|
|
|
|
if (same_buft && buf->iface.set_tensor_n != NULL) {
|
|
buf->iface.set_tensor_n(buf, tensors, data_ptrs.data(), offsets, sizes, n_tensors);
|
|
return;
|
|
}
|
|
|
|
if (!same_buft) {
|
|
std::vector<std::vector<size_t>> groups;
|
|
ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) {
|
|
return tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer;
|
|
}, groups);
|
|
|
|
for (size_t g = 0; g < groups.size(); g++) {
|
|
std::vector<ggml_tensor *> g_tensors;
|
|
std::vector<size_t> g_offsets;
|
|
std::vector<size_t> g_sizes;
|
|
std::vector<size_t> g_data_offsets;
|
|
g_tensors.reserve(groups[g].size());
|
|
g_offsets.reserve(groups[g].size());
|
|
g_sizes.reserve(groups[g].size());
|
|
g_data_offsets.reserve(groups[g].size());
|
|
|
|
for (size_t i : groups[g]) {
|
|
g_tensors.push_back(tensors[i]);
|
|
g_offsets.push_back(offsets[i]);
|
|
g_sizes.push_back(sizes[i]);
|
|
g_data_offsets.push_back(data_offsets[i]);
|
|
}
|
|
|
|
ggml_backend_tensor_set_n(g_tensors.data(), data, g_offsets.data(), g_sizes.data(), g_data_offsets.data(), g_tensors.size());
|
|
}
|
|
return;
|
|
}
|
|
|
|
size_t base_offset = 0, size = 0, stride_tensor = 0, stride_data = 0;
|
|
if (ggml_backend_tensor_batch_is_2d(tensors, offsets, sizes, data_offsets, n_tensors,
|
|
&base_offset, &size, &stride_tensor, &stride_data)) {
|
|
ggml_backend_tensor_set_2d(tensors[0], data_ptrs[0], base_offset, size,
|
|
n_tensors, stride_tensor, stride_data);
|
|
return;
|
|
}
|
|
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
ggml_backend_tensor_set(tensors[i], data_ptrs[i], offsets[i], sizes[i]);
|
|
}
|
|
}
|
|
|
|
void ggml_backend_tensor_get_n(const struct ggml_tensor * const * tensors, void * data,
|
|
const size_t * offsets, const size_t * sizes, const size_t * data_offsets, size_t n_tensors) {
|
|
if (n_tensors == 0) {
|
|
return;
|
|
}
|
|
|
|
std::vector<void *> data_ptrs(n_tensors);
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
data_ptrs[i] = (char *) data + data_offsets[i];
|
|
}
|
|
|
|
ggml_backend_buffer_t buf = NULL;
|
|
bool same_buft = true;
|
|
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
GGML_ASSERT(tensors[i] != NULL);
|
|
ggml_backend_buffer_t tensor_buf = tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer;
|
|
GGML_ASSERT(tensor_buf != NULL && "tensor buffer not set");
|
|
GGML_ASSERT(tensors[i]->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offsets[i] + sizes[i] <= ggml_nbytes(tensors[i]) && "tensor read out of bounds");
|
|
|
|
if (buf == NULL) {
|
|
buf = tensor_buf;
|
|
} else if (buf->buft != tensor_buf->buft) {
|
|
same_buft = false;
|
|
}
|
|
}
|
|
|
|
if (same_buft && buf->iface.get_tensor_n != NULL) {
|
|
buf->iface.get_tensor_n(buf, tensors, data_ptrs.data(), offsets, sizes, n_tensors);
|
|
return;
|
|
}
|
|
|
|
if (!same_buft) {
|
|
std::vector<std::vector<size_t>> groups;
|
|
ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) {
|
|
return tensors[i]->view_src ? tensors[i]->view_src->buffer : tensors[i]->buffer;
|
|
}, groups);
|
|
|
|
for (size_t g = 0; g < groups.size(); g++) {
|
|
std::vector<const ggml_tensor *> g_tensors;
|
|
std::vector<size_t> g_offsets;
|
|
std::vector<size_t> g_sizes;
|
|
std::vector<size_t> g_data_offsets;
|
|
g_tensors.reserve(groups[g].size());
|
|
g_offsets.reserve(groups[g].size());
|
|
g_sizes.reserve(groups[g].size());
|
|
g_data_offsets.reserve(groups[g].size());
|
|
|
|
for (size_t i : groups[g]) {
|
|
g_tensors.push_back(tensors[i]);
|
|
g_offsets.push_back(offsets[i]);
|
|
g_sizes.push_back(sizes[i]);
|
|
g_data_offsets.push_back(data_offsets[i]);
|
|
}
|
|
|
|
ggml_backend_tensor_get_n(g_tensors.data(), data, g_offsets.data(), g_sizes.data(), g_data_offsets.data(), g_tensors.size());
|
|
}
|
|
return;
|
|
}
|
|
|
|
size_t base_offset = 0, size = 0, stride_tensor = 0, stride_data = 0;
|
|
if (ggml_backend_tensor_batch_is_2d(tensors, offsets, sizes, data_offsets, n_tensors,
|
|
&base_offset, &size, &stride_tensor, &stride_data)) {
|
|
ggml_backend_tensor_get_2d(tensors[0], data_ptrs[0], base_offset, size,
|
|
n_tensors, stride_tensor, stride_data);
|
|
return;
|
|
}
|
|
|
|
for (size_t i = 0; i < n_tensors; i++) {
|
|
ggml_backend_tensor_get(tensors[i], data_ptrs[i], offsets[i], sizes[i]);
|
|
}
|
|
}
|
|
|
|
void ggml_backend_tensor_memset(struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size) {
|
|
GGML_ASSERT(tensor);
|
|
ggml_backend_buffer_t buf = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
|
|
if (size == 0) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(buf != NULL && "tensor buffer not set");
|
|
GGML_ASSERT(tensor->data != NULL && "tensor not allocated");
|
|
GGML_ASSERT(offset + size <= ggml_nbytes(tensor) && "tensor write out of bounds");
|
|
GGML_ASSERT(buf->iface.memset_tensor != NULL && "memset not implemented by backend buffer");
|
|
|
|
buf->iface.memset_tensor(buf, tensor, value, offset, size);
|
|
}
|
|
|
|
void ggml_backend_synchronize(ggml_backend_t backend) {
|
|
GGML_ASSERT(backend);
|
|
if (backend->iface.synchronize == NULL) {
|
|
return;
|
|
}
|
|
|
|
backend->iface.synchronize(backend);
|
|
}
|
|
|
|
void ggml_backend_free_scratch(ggml_backend_t backend) {
|
|
GGML_ASSERT(backend);
|
|
if (backend->iface.free_scratch == NULL) {
|
|
return;
|
|
}
|
|
|
|
backend->iface.free_scratch(backend);
|
|
}
|
|
|
|
ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(backend->iface.graph_plan_create != NULL);
|
|
|
|
return backend->iface.graph_plan_create(backend, cgraph);
|
|
}
|
|
|
|
void ggml_backend_graph_plan_free(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(backend->iface.graph_plan_free != NULL);
|
|
|
|
backend->iface.graph_plan_free(backend, plan);
|
|
}
|
|
|
|
enum ggml_status ggml_backend_graph_plan_compute(ggml_backend_t backend, ggml_backend_graph_plan_t plan) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(backend->iface.graph_plan_compute != NULL);
|
|
|
|
return backend->iface.graph_plan_compute(backend, plan);
|
|
}
|
|
|
|
enum ggml_status ggml_backend_graph_compute(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
|
|
enum ggml_status err = ggml_backend_graph_compute_async(backend, cgraph);
|
|
ggml_backend_synchronize(backend);
|
|
return err;
|
|
}
|
|
|
|
enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph) {
|
|
GGML_ASSERT(backend);
|
|
return backend->iface.graph_compute(backend, cgraph);
|
|
}
|
|
|
|
bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op) {
|
|
GGML_ASSERT(backend);
|
|
return ggml_backend_dev_supports_op(backend->device, op);
|
|
}
|
|
|
|
bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(backend);
|
|
return ggml_backend_dev_supports_buft(backend->device, buft);
|
|
}
|
|
|
|
bool ggml_backend_offload_op(ggml_backend_t backend, const struct ggml_tensor * op) {
|
|
GGML_ASSERT(backend);
|
|
return ggml_backend_dev_offload_op(backend->device, op);
|
|
}
|
|
|
|
ggml_backend_dev_t ggml_backend_get_device(ggml_backend_t backend) {
|
|
GGML_ASSERT(backend);
|
|
return backend->device;
|
|
}
|
|
|
|
// backend copy
|
|
|
|
void ggml_backend_tensor_copy(const struct ggml_tensor * src, struct ggml_tensor * dst) {
|
|
GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
|
|
|
|
if (src == dst) {
|
|
return;
|
|
}
|
|
|
|
if (ggml_backend_buffer_is_host(src->buffer)) {
|
|
ggml_backend_tensor_set(dst, src->data, 0, ggml_nbytes(src));
|
|
} else if (ggml_backend_buffer_is_host(dst->buffer)) {
|
|
ggml_backend_tensor_get(src, dst->data, 0, ggml_nbytes(src));
|
|
} else if (!ggml_backend_buffer_copy_tensor(src, dst)) {
|
|
#ifndef NDEBUG
|
|
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));
|
|
#endif // NDEBUG
|
|
size_t nbytes = ggml_nbytes(src);
|
|
void * data = malloc(nbytes);
|
|
ggml_backend_tensor_get(src, data, 0, nbytes);
|
|
ggml_backend_tensor_set(dst, data, 0, nbytes);
|
|
free(data);
|
|
}
|
|
}
|
|
|
|
void ggml_backend_tensor_copy_n(const struct ggml_tensor * const * srcs, struct ggml_tensor * const * dsts, size_t n_tensors) {
|
|
if (n_tensors == 0) {
|
|
return;
|
|
}
|
|
|
|
for (size_t i = 0; i < n_tensors; ++i) {
|
|
GGML_ASSERT(ggml_are_same_layout(srcs[i], dsts[i]) && "cannot copy tensors with different layouts");
|
|
}
|
|
|
|
ggml_backend_buffer_t buf = dsts[0]->view_src ? dsts[0]->view_src->buffer : dsts[0]->buffer;
|
|
bool same_buft = true;
|
|
for (size_t i = 0; i < n_tensors; ++i) {
|
|
ggml_backend_buffer_t dst_buf = dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer;
|
|
if (dst_buf->buft != buf->buft) {
|
|
same_buft = false;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// if cpy_tensor_n returns false, it must not have performed any copies
|
|
if (same_buft && buf->iface.cpy_tensor_n != NULL) {
|
|
if (buf->iface.cpy_tensor_n(buf, srcs, dsts, n_tensors)) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
if (!same_buft) {
|
|
std::vector<std::vector<size_t>> groups;
|
|
ggml_backend_tensor_buft_groups(n_tensors, [&](size_t i) {
|
|
return dsts[i]->view_src ? dsts[i]->view_src->buffer : dsts[i]->buffer;
|
|
}, groups);
|
|
|
|
for (size_t g = 0; g < groups.size(); g++) {
|
|
std::vector<const ggml_tensor *> g_srcs;
|
|
std::vector<ggml_tensor *> g_dsts;
|
|
g_srcs.reserve(groups[g].size());
|
|
g_dsts.reserve(groups[g].size());
|
|
|
|
for (size_t i : groups[g]) {
|
|
g_srcs.push_back(srcs[i]);
|
|
g_dsts.push_back(dsts[i]);
|
|
}
|
|
|
|
ggml_backend_tensor_copy_n(g_srcs.data(), g_dsts.data(), g_srcs.size());
|
|
}
|
|
return;
|
|
}
|
|
|
|
for (size_t i = 0; i < n_tensors; ++i) {
|
|
ggml_backend_tensor_copy(srcs[i], dsts[i]);
|
|
}
|
|
}
|
|
|
|
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) {
|
|
GGML_ASSERT(ggml_are_same_layout(src, dst) && "cannot copy tensors with different layouts");
|
|
|
|
if (src == dst) {
|
|
return;
|
|
}
|
|
|
|
GGML_ASSERT(backend_dst);
|
|
if (backend_dst->iface.cpy_tensor_async != NULL) {
|
|
if (backend_dst->iface.cpy_tensor_async(backend_src, backend_dst, src, dst)) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
// an async copy would normally happen after all the queued operations on both backends are completed
|
|
// to simulate the same behavior, we need to synchronize both backends first, and do a blocking copy
|
|
ggml_backend_synchronize(backend_src);
|
|
ggml_backend_synchronize(backend_dst);
|
|
ggml_backend_tensor_copy(src, dst);
|
|
}
|
|
|
|
// events
|
|
|
|
ggml_backend_event_t ggml_backend_event_new(ggml_backend_dev_t device) {
|
|
// null device is allowed for the transition period to the device interface
|
|
if (device == NULL || device->iface.event_new == NULL) {
|
|
return NULL;
|
|
}
|
|
return device->iface.event_new(device);
|
|
}
|
|
|
|
void ggml_backend_event_free(ggml_backend_event_t event) {
|
|
if (event == NULL) {
|
|
return;
|
|
}
|
|
event->device->iface.event_free(event->device, event);
|
|
}
|
|
|
|
void ggml_backend_event_record(ggml_backend_event_t event, ggml_backend_t backend) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(backend->iface.event_record != NULL);
|
|
|
|
backend->iface.event_record(backend, event);
|
|
}
|
|
|
|
void ggml_backend_event_synchronize(ggml_backend_event_t event) {
|
|
GGML_ASSERT(event);
|
|
GGML_ASSERT(event->device->iface.event_synchronize);
|
|
|
|
event->device->iface.event_synchronize(event->device, event);
|
|
}
|
|
|
|
void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
|
|
GGML_ASSERT(backend);
|
|
GGML_ASSERT(backend->iface.event_wait != NULL);
|
|
|
|
backend->iface.event_wait(backend, event);
|
|
}
|
|
|
|
static void ggml_backend_graph_optimize(ggml_backend_t backend, struct ggml_cgraph * cgraph, struct ggml_backend_graph_optimize_params * params) {
|
|
GGML_ASSERT(backend);
|
|
if (backend->iface.graph_optimize != NULL) {
|
|
backend->iface.graph_optimize(backend, cgraph, params);
|
|
}
|
|
}
|
|
|
|
// Backend device
|
|
|
|
const char * ggml_backend_dev_name(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.get_name(device);
|
|
}
|
|
|
|
const char * ggml_backend_dev_description(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.get_description(device);
|
|
}
|
|
|
|
void ggml_backend_dev_memory(ggml_backend_dev_t device, size_t * free, size_t * total) {
|
|
GGML_ASSERT(device);
|
|
device->iface.get_memory(device, free, total);
|
|
}
|
|
|
|
enum ggml_backend_dev_type ggml_backend_dev_type(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.get_type(device);
|
|
}
|
|
|
|
void ggml_backend_dev_get_props(ggml_backend_dev_t device, struct ggml_backend_dev_props * props) {
|
|
GGML_ASSERT(device);
|
|
memset(props, 0, sizeof(*props));
|
|
device->iface.get_props(device, props);
|
|
}
|
|
|
|
ggml_backend_reg_t ggml_backend_dev_backend_reg(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
return device->reg;
|
|
}
|
|
|
|
ggml_backend_t ggml_backend_dev_init(ggml_backend_dev_t device, const char * params) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.init_backend(device, params);
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_dev_buffer_type(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.get_buffer_type(device);
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_dev_host_buffer_type(ggml_backend_dev_t device) {
|
|
GGML_ASSERT(device);
|
|
if (device->iface.get_host_buffer_type == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
return device->iface.get_host_buffer_type(device);
|
|
}
|
|
|
|
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) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.buffer_from_host_ptr(device, ptr, size, max_tensor_size);
|
|
}
|
|
|
|
bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.supports_op(device, op);
|
|
}
|
|
|
|
bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft) {
|
|
GGML_ASSERT(device);
|
|
return device->iface.supports_buft(device, buft);
|
|
}
|
|
|
|
bool ggml_backend_dev_offload_op(ggml_backend_dev_t device, const struct ggml_tensor * op) {
|
|
GGML_ASSERT(device);
|
|
if (device->iface.offload_op != NULL) {
|
|
return device->iface.offload_op(device, op);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// Backend (reg)
|
|
|
|
const char * ggml_backend_reg_name(ggml_backend_reg_t reg) {
|
|
GGML_ASSERT(reg);
|
|
return reg->iface.get_name(reg);
|
|
}
|
|
|
|
size_t ggml_backend_reg_dev_count(ggml_backend_reg_t reg) {
|
|
GGML_ASSERT(reg);
|
|
return reg->iface.get_device_count(reg);
|
|
}
|
|
|
|
ggml_backend_dev_t ggml_backend_reg_dev_get(ggml_backend_reg_t reg, size_t index) {
|
|
GGML_ASSERT(reg);
|
|
return reg->iface.get_device(reg, index);
|
|
}
|
|
|
|
void * ggml_backend_reg_get_proc_address(ggml_backend_reg_t reg, const char * name) {
|
|
GGML_ASSERT(reg);
|
|
if (!reg->iface.get_proc_address) {
|
|
return NULL;
|
|
}
|
|
return reg->iface.get_proc_address(reg, name);
|
|
}
|
|
|
|
// multi-buffer buffer
|
|
|
|
struct ggml_backend_multi_buffer_context {
|
|
ggml_backend_buffer_t * buffers;
|
|
size_t n_buffers;
|
|
};
|
|
|
|
static void ggml_backend_multi_buffer_free_buffer(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context;
|
|
for (size_t i = 0; i < ctx->n_buffers; i++) {
|
|
ggml_backend_buffer_free(ctx->buffers[i]);
|
|
}
|
|
|
|
free(ctx->buffers);
|
|
free(ctx);
|
|
}
|
|
|
|
static void ggml_backend_multi_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
|
|
GGML_ASSERT(buffer);
|
|
ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context;
|
|
for (size_t i = 0; i < ctx->n_buffers; i++) {
|
|
ggml_backend_buffer_clear(ctx->buffers[i], value);
|
|
}
|
|
}
|
|
|
|
static const struct ggml_backend_buffer_i ggml_backend_multi_buffer_i = {
|
|
/* .free_buffer = */ ggml_backend_multi_buffer_free_buffer,
|
|
/* .get_base = */ NULL,
|
|
/* .init_tensor = */ NULL,
|
|
/* .memset_tensor = */ NULL,
|
|
/* .set_tensor = */ NULL,
|
|
/* .get_tensor = */ NULL,
|
|
/* .set_tensor_2d = */ NULL,
|
|
/* .get_tensor_2d = */ NULL,
|
|
/* .cpy_tensor = */ NULL,
|
|
/* .clear = */ ggml_backend_multi_buffer_clear,
|
|
/* .reset = */ NULL,
|
|
/* .set_tensor_n = */ NULL,
|
|
/* .get_tensor_n = */ NULL,
|
|
/* .cpy_tensor_n = */ NULL,
|
|
};
|
|
|
|
ggml_backend_buffer_t ggml_backend_multi_buffer_alloc_buffer(ggml_backend_buffer_t * buffers, size_t n_buffers) {
|
|
ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) malloc(sizeof(struct ggml_backend_multi_buffer_context));
|
|
ctx->n_buffers = n_buffers;
|
|
ctx->buffers = (ggml_backend_buffer_t *) malloc(n_buffers * sizeof(ggml_backend_buffer_t));
|
|
|
|
GGML_ASSERT(ctx->buffers != NULL);
|
|
|
|
size_t total_size = 0;
|
|
for (size_t i = 0; i < n_buffers; i++) {
|
|
ctx->buffers[i] = buffers[i];
|
|
total_size += ggml_backend_buffer_get_size(buffers[i]);
|
|
}
|
|
|
|
return ggml_backend_buffer_init(buffers[0]->buft, ggml_backend_multi_buffer_i, ctx, total_size);
|
|
}
|
|
|
|
bool ggml_backend_buffer_is_multi_buffer(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
return buffer->iface.free_buffer == ggml_backend_multi_buffer_free_buffer;
|
|
}
|
|
|
|
void ggml_backend_multi_buffer_set_usage(ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage) {
|
|
GGML_ASSERT(buffer);
|
|
GGML_ASSERT(ggml_backend_buffer_is_multi_buffer(buffer));
|
|
ggml_backend_multi_buffer_context * ctx = (ggml_backend_multi_buffer_context *) buffer->context;
|
|
for (size_t i = 0; i < ctx->n_buffers; i++) {
|
|
ggml_backend_buffer_set_usage(ctx->buffers[i], usage);
|
|
}
|
|
}
|
|
|
|
// creates a copy of the tensor with the same memory layout
|
|
static struct ggml_tensor * ggml_dup_tensor_layout(struct ggml_context * ctx, const struct ggml_tensor * tensor) {
|
|
struct ggml_tensor * dup = ggml_dup_tensor(ctx, tensor);
|
|
for (int i = 0; i < GGML_MAX_DIMS; i++) {
|
|
dup->nb[i] = tensor->nb[i];
|
|
}
|
|
return dup;
|
|
}
|
|
|
|
static bool ggml_is_view_op(enum ggml_op op) {
|
|
return op == GGML_OP_VIEW || op == GGML_OP_RESHAPE || op == GGML_OP_PERMUTE || op == GGML_OP_TRANSPOSE;
|
|
}
|
|
|
|
// scheduler
|
|
|
|
#ifndef GGML_SCHED_MAX_BACKENDS
|
|
#define GGML_SCHED_MAX_BACKENDS 16
|
|
#endif
|
|
|
|
#ifndef GGML_SCHED_MAX_SPLIT_INPUTS
|
|
#define GGML_SCHED_MAX_SPLIT_INPUTS 30
|
|
#endif
|
|
|
|
#ifndef GGML_SCHED_MAX_COPIES
|
|
#define GGML_SCHED_MAX_COPIES 4
|
|
#endif
|
|
|
|
struct ggml_backend_sched_split {
|
|
int backend_id;
|
|
int i_start;
|
|
int i_end;
|
|
struct ggml_tensor ** inputs;
|
|
int n_inputs;
|
|
int inputs_capacity;
|
|
// graph view of this split
|
|
struct ggml_cgraph graph;
|
|
};
|
|
|
|
struct ggml_backend_sched {
|
|
bool is_reset; // true if the scheduler has been reset since the last graph split
|
|
bool is_alloc;
|
|
|
|
int n_backends;
|
|
|
|
ggml_backend_t backends[GGML_SCHED_MAX_BACKENDS];
|
|
ggml_backend_buffer_type_t bufts[GGML_SCHED_MAX_BACKENDS];
|
|
ggml_gallocr_t galloc;
|
|
|
|
// hash map of the nodes in the graph
|
|
struct ggml_hash_set hash_set;
|
|
int * hv_tensor_backend_ids; // [hash_set.size]
|
|
struct ggml_tensor ** hv_tensor_copies; // [hash_set.size][n_backends][n_copies]
|
|
bool * hv_tensor_requires_copy; // [hash_set.size] decides if input needs to be copied to each split
|
|
|
|
int * node_backend_ids; // [graph_size]
|
|
int * leaf_backend_ids; // [graph_size]
|
|
|
|
int * prev_node_backend_ids; // [graph_size]
|
|
int * prev_leaf_backend_ids; // [graph_size]
|
|
|
|
// copy of the graph with modified inputs
|
|
struct ggml_cgraph graph;
|
|
|
|
// graph splits
|
|
struct ggml_backend_sched_split * splits;
|
|
int n_splits;
|
|
int splits_capacity;
|
|
|
|
// pipeline parallelism support
|
|
int n_copies;
|
|
int cur_copy;
|
|
int next_copy;
|
|
ggml_backend_event_t events[GGML_SCHED_MAX_BACKENDS][GGML_SCHED_MAX_COPIES];
|
|
struct ggml_tensor ** graph_inputs;
|
|
int n_graph_inputs;
|
|
int graph_inputs_capacity;
|
|
|
|
struct ggml_context * ctx;
|
|
|
|
ggml_backend_sched_eval_callback callback_eval;
|
|
void * callback_eval_user_data;
|
|
|
|
ggml_backend_sched_copy_callback callback_copy;
|
|
void * callback_copy_user_data;
|
|
|
|
ggml_backend_sched_realloc_callback callback_realloc;
|
|
void * callback_realloc_user_data;
|
|
|
|
char * context_buffer;
|
|
size_t context_buffer_size;
|
|
|
|
bool op_offload;
|
|
|
|
int debug;
|
|
|
|
// graph size of the current and the previous scheduling, used by the realloc callback and for debugging
|
|
// graph reallocations [GGML_SCHED_DEBUG_REALLOC]
|
|
// ref: https://github.com/ggml-org/llama.cpp/pull/17617
|
|
int graph_size;
|
|
int prev_graph_size;
|
|
|
|
int debug_realloc;
|
|
|
|
// inputs of the next split read from the backend of the current split before it computes, see ggml_backend_sched_prefetch_inputs
|
|
ggml_backend_event_t prefetch_events[GGML_SCHED_MAX_BACKENDS]; // created on first use, NULL if the backend has no events
|
|
bool prefetch_tried [GGML_SCHED_MAX_BACKENDS];
|
|
struct ggml_tensor * prefetched[GGML_SCHED_MAX_SPLIT_INPUTS];
|
|
int n_prefetched;
|
|
int prefetch_split; // the split that reads the prefetched inputs
|
|
int prefetch_backend_id; // the backend that copies them
|
|
};
|
|
|
|
#define hash_id(tensor) ggml_hash_find_or_insert(&sched->hash_set, tensor)
|
|
#define tensor_backend_id(tensor) sched->hv_tensor_backend_ids[hash_id(tensor)]
|
|
#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)]
|
|
#define tensor_copy(tensor, backend_id, copy_id) tensor_id_copy(hash_id(tensor), backend_id, copy_id)
|
|
|
|
static void ggml_backend_sched_split_inputs_grow(struct ggml_backend_sched_split * split) {
|
|
int new_cap = GGML_SCHED_MAX_SPLIT_INPUTS;
|
|
if (split->inputs_capacity > 0) {
|
|
new_cap = 2*split->inputs_capacity;
|
|
GGML_LOG_DEBUG("%s: increasing split inputs capacity from %d to %d\n", __func__, split->inputs_capacity, new_cap);
|
|
}
|
|
auto * pnew = (struct ggml_tensor **) realloc((void *) split->inputs, new_cap * sizeof(struct ggml_tensor *));
|
|
if (pnew == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate %zu bytes\n", __func__, new_cap * sizeof(struct ggml_tensor *));
|
|
GGML_ABORT("failed to grow split inputs container");
|
|
}
|
|
split->inputs = pnew;
|
|
split->inputs_capacity = new_cap;
|
|
}
|
|
|
|
static void ggml_backend_sched_graph_inputs_grow(ggml_backend_sched_t sched) {
|
|
int new_cap = GGML_SCHED_MAX_SPLIT_INPUTS;
|
|
if (sched->graph_inputs_capacity > 0) {
|
|
new_cap = 2*sched->graph_inputs_capacity;
|
|
GGML_LOG_DEBUG("%s: increasing graph inputs capacity from %d to %d\n", __func__, sched->graph_inputs_capacity, new_cap);
|
|
}
|
|
auto * pnew = (struct ggml_tensor **) realloc((void *) sched->graph_inputs, new_cap * sizeof(struct ggml_tensor *));
|
|
if (pnew == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate %zu bytes\n", __func__, new_cap * sizeof(struct ggml_tensor *));
|
|
GGML_ABORT("failed to grow graph inputs container");
|
|
}
|
|
sched->graph_inputs = pnew;
|
|
sched->graph_inputs_capacity = new_cap;
|
|
}
|
|
|
|
// returns the priority of the backend, lower id is higher priority
|
|
static int ggml_backend_sched_backend_id(ggml_backend_sched_t sched, ggml_backend_t backend) {
|
|
for (int i = 0; i < sched->n_backends; i++) {
|
|
if (sched->backends[i] == backend) {
|
|
return i;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
static int ggml_backend_sched_backend_from_buffer(ggml_backend_sched_t sched, const struct ggml_tensor * tensor, const struct ggml_tensor * op) {
|
|
ggml_backend_buffer_t buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
if (buffer == NULL) {
|
|
return -1;
|
|
}
|
|
|
|
// find highest prio backend that supports the buffer type and the op
|
|
for (int i = 0; i < sched->n_backends; i++) {
|
|
if (ggml_backend_supports_buft(sched->backends[i], buffer->buft) &&
|
|
ggml_backend_supports_op(sched->backends[i], op)) {
|
|
return i;
|
|
}
|
|
}
|
|
|
|
#ifndef NDEBUG
|
|
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",
|
|
__func__, ggml_op_desc(tensor), ggml_backend_buffer_name(buffer), tensor->name);
|
|
#endif
|
|
|
|
return -1;
|
|
}
|
|
|
|
#if 0
|
|
#define GGML_SCHED_MAX_SPLITS_DEBUG 4096
|
|
static char causes[GGML_DEFAULT_GRAPH_SIZE*16 + GGML_SCHED_MAX_SPLITS_DEBUG*GGML_SCHED_MAX_SPLIT_INPUTS][128]; // debug only
|
|
#define SET_CAUSE(node, ...) sprintf(causes[hash_id(node)], __VA_ARGS__)
|
|
#define GET_CAUSE(node) causes[hash_id(node)]
|
|
#else
|
|
#define SET_CAUSE(node, ...)
|
|
#define GET_CAUSE(node) ""
|
|
#endif
|
|
|
|
// returns the backend that should be used for the node based on the current locations
|
|
static int ggml_backend_sched_backend_id_from_cur(ggml_backend_sched_t sched, struct ggml_tensor * tensor) {
|
|
// assign pre-allocated nodes to their backend
|
|
int cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor, tensor);
|
|
if (cur_backend_id != -1) {
|
|
SET_CAUSE(tensor, "1.dst");
|
|
return cur_backend_id;
|
|
}
|
|
|
|
// view_src
|
|
if (tensor->view_src != NULL) {
|
|
cur_backend_id = ggml_backend_sched_backend_from_buffer(sched, tensor->view_src, tensor);
|
|
if (cur_backend_id != -1) {
|
|
SET_CAUSE(tensor, "1.vsrc");
|
|
return cur_backend_id;
|
|
}
|
|
}
|
|
|
|
if (tensor->buffer || (tensor->view_src && tensor->view_src->buffer)) {
|
|
// since the tensor is pre-allocated, it cannot be moved to another backend
|
|
ggml_backend_buffer_t buffer = tensor->view_src ? tensor->view_src->buffer : tensor->buffer;
|
|
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));
|
|
}
|
|
|
|
// graph input
|
|
if (tensor->flags & GGML_TENSOR_FLAG_INPUT) {
|
|
cur_backend_id = sched->n_backends - 1; // last backend (assumed CPU)
|
|
SET_CAUSE(tensor, "1.inp");
|
|
return cur_backend_id;
|
|
}
|
|
|
|
// operations with weights are preferably run on the same backend as the weights
|
|
// TODO: there are exceptions (see below) - not an ideal solution
|
|
bool allow = true;
|
|
|
|
// skip ROPE since the rope freqs tensor is too small to choose a backend based on it
|
|
allow = allow && tensor->op != GGML_OP_ROPE;
|
|
|
|
// skip FLASH_ATTN_EXT since the sinks tensor is too small to choose a based based on it
|
|
allow = allow && tensor->op != GGML_OP_FLASH_ATTN_EXT;
|
|
|
|
if (allow) {
|
|
for (int i = 0; i < GGML_MAX_SRC; i++) {
|
|
const struct ggml_tensor * src = tensor->src[i];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
|
|
int src_backend_id = ggml_backend_sched_backend_from_buffer(sched, src, tensor);
|
|
// check if a backend with higher prio wants to offload the op
|
|
if (sched->op_offload && src_backend_id == sched->n_backends - 1 && ggml_backend_buffer_is_host(src->buffer)) {
|
|
for (int b = 0; b < src_backend_id; b++) {
|
|
if (ggml_backend_supports_op(sched->backends[b], tensor) && ggml_backend_offload_op(sched->backends[b], tensor)) {
|
|
SET_CAUSE(tensor, "1.off");
|
|
return b;
|
|
}
|
|
}
|
|
}
|
|
SET_CAUSE(tensor, "1.wgt%d", i);
|
|
return src_backend_id;
|
|
}
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
|
|
static char * fmt_size(size_t size) {
|
|
static char buffer[128];
|
|
if (size >= 1024*1024) {
|
|
snprintf(buffer, sizeof(buffer), "%zuM", size/1024/1024);
|
|
} else {
|
|
snprintf(buffer, sizeof(buffer), "%zuK", size/1024);
|
|
}
|
|
return buffer;
|
|
}
|
|
|
|
static void ggml_backend_sched_print_assignments(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
|
|
int cur_split = 0;
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
if (cur_split < sched->n_splits && i == sched->splits[cur_split].i_start) {
|
|
ggml_backend_t split_backend = sched->backends[sched->splits[cur_split].backend_id];
|
|
GGML_LOG_DEBUG("\n## SPLIT #%d: %s # %d inputs", cur_split, ggml_backend_name(split_backend),
|
|
sched->splits[cur_split].n_inputs);
|
|
for (int j = 0; j < sched->splits[cur_split].n_inputs; j++) {
|
|
if (j == 0) {
|
|
GGML_LOG_DEBUG(": ");
|
|
}
|
|
GGML_LOG_DEBUG("[%s (%5.5s)] ", sched->splits[cur_split].inputs[j]->name,
|
|
fmt_size(ggml_nbytes(sched->splits[cur_split].inputs[j])));
|
|
}
|
|
GGML_LOG_DEBUG("\n");
|
|
cur_split++;
|
|
}
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
if (sched->debug > 1) {
|
|
ggml_backend_t tensor_backend = ggml_backend_sched_get_tensor_backend(sched, node);
|
|
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,
|
|
fmt_size(ggml_nbytes(node)), tensor_backend ? ggml_backend_name(tensor_backend) : "NULL", GET_CAUSE(node),
|
|
graph->use_counts[ggml_hash_find(&graph->visited_hash_set, node)], node->flags & GGML_TENSOR_FLAG_COMPUTE ? 1 : 0);
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
ggml_backend_t src_backend = ggml_backend_sched_get_tensor_backend(sched, src);
|
|
GGML_LOG_DEBUG(" %20.20s (%5.5s) [%5.5s %8.8s]", src->name,
|
|
fmt_size(ggml_nbytes(src)), src_backend ? ggml_backend_name(src_backend) : "NULL", GET_CAUSE(src));
|
|
}
|
|
GGML_LOG_DEBUG("\n");
|
|
}
|
|
}
|
|
}
|
|
|
|
static bool ggml_backend_sched_buffer_supported(ggml_backend_sched_t sched, struct ggml_tensor * t, int backend_id) {
|
|
ggml_backend_buffer_t buf = t->view_src ? t->view_src->buffer : t->buffer;
|
|
ggml_backend_buffer_type_t buft = NULL;
|
|
|
|
if (buf) {
|
|
// the tensor is already allocated
|
|
buft = buf->buft;
|
|
} else {
|
|
// see if the tensor already has a backend assigned, and use the buffer type of that backend
|
|
int tensor_backend_id = tensor_backend_id(t);
|
|
if (tensor_backend_id == -1 && t->view_src) {
|
|
tensor_backend_id = tensor_backend_id(t->view_src);
|
|
}
|
|
if (tensor_backend_id != -1) {
|
|
buft = sched->bufts[tensor_backend_id];
|
|
}
|
|
}
|
|
|
|
return buft != NULL && ggml_backend_supports_buft(sched->backends[backend_id], buft);
|
|
}
|
|
|
|
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) {
|
|
if (ggml_backend_supports_op(sched->backends[cur_backend_id], node)) {
|
|
*node_backend_id = cur_backend_id;
|
|
SET_CAUSE(node, "2.sup");
|
|
}
|
|
}
|
|
|
|
// assigns backends to ops and splits the graph into subgraphs that can be computed on the same backend
|
|
void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
|
|
// reset splits
|
|
sched->n_splits = 0;
|
|
sched->n_graph_inputs = 0;
|
|
sched->is_reset = false;
|
|
|
|
struct ggml_init_params params = {
|
|
/* .mem_size = */ sched->context_buffer_size,
|
|
/* .mem_buffer = */ sched->context_buffer,
|
|
/* .no_alloc = */ true
|
|
};
|
|
|
|
ggml_free(sched->ctx);
|
|
|
|
sched->ctx = ggml_init(params);
|
|
if (sched->ctx == NULL) {
|
|
GGML_ABORT("%s: failed to initialize context\n", __func__);
|
|
}
|
|
|
|
graph->uid = ggml_graph_next_uid();
|
|
|
|
// pass 1: assign backends to ops with pre-allocated inputs
|
|
for (int i = 0; i < graph->n_leafs; i++) {
|
|
struct ggml_tensor * leaf = graph->leafs[i];
|
|
int * leaf_backend_id = &tensor_backend_id(leaf);
|
|
// do not overwrite user assignments
|
|
if (*leaf_backend_id == -1) {
|
|
*leaf_backend_id = ggml_backend_sched_backend_id_from_cur(sched, leaf);
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
// do not overwrite user assignments
|
|
if (*node_backend_id == -1) {
|
|
*node_backend_id = ggml_backend_sched_backend_id_from_cur(sched, node);
|
|
|
|
#if 0
|
|
// src
|
|
if (node->op == GGML_OP_NONE) {
|
|
continue;
|
|
}
|
|
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
int * src_backend_id = &tensor_backend_id(src);
|
|
if (*src_backend_id == -1) {
|
|
*src_backend_id = ggml_backend_sched_backend_id_from_cur(sched, src);
|
|
}
|
|
}
|
|
#endif
|
|
}
|
|
}
|
|
|
|
// pass 2: expand current backend assignments
|
|
// assign the same backend to adjacent nodes
|
|
// expand gpu backends (i.e. non last prio) up and down, ignoring cpu (the lowest priority backend)
|
|
// thus, cpu will never be used unless weights are on cpu, or there are no gpu ops between cpu ops
|
|
// 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
|
|
// expand gpu down
|
|
{
|
|
int cur_backend_id = -1;
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
if (*node_backend_id != -1) {
|
|
if (*node_backend_id == sched->n_backends - 1) {
|
|
// skip cpu (lowest prio backend)
|
|
cur_backend_id = -1;
|
|
} else {
|
|
cur_backend_id = *node_backend_id;
|
|
}
|
|
} else if (cur_backend_id != -1) {
|
|
ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
|
|
}
|
|
}
|
|
}
|
|
// expand gpu up
|
|
{
|
|
int cur_backend_id = -1;
|
|
for (int i = graph->n_nodes - 1; i >= 0; i--) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
if (*node_backend_id != -1) {
|
|
if (*node_backend_id == sched->n_backends - 1) {
|
|
// skip cpu (lowest prio backend)
|
|
cur_backend_id = -1;
|
|
} else {
|
|
cur_backend_id = *node_backend_id;
|
|
}
|
|
} else if (cur_backend_id != -1) {
|
|
ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
|
|
}
|
|
}
|
|
}
|
|
// expand rest down
|
|
{
|
|
int cur_backend_id = -1;
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
if (*node_backend_id != -1) {
|
|
cur_backend_id = *node_backend_id;
|
|
} else if (cur_backend_id != -1) {
|
|
ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
|
|
}
|
|
}
|
|
}
|
|
// expand rest up
|
|
{
|
|
int cur_backend_id = -1;
|
|
for (int i = graph->n_nodes - 1; i >= 0; i--) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
if (*node_backend_id != -1) {
|
|
cur_backend_id = *node_backend_id;
|
|
} else if (cur_backend_id != -1) {
|
|
ggml_backend_sched_set_if_supported(sched, node, cur_backend_id, node_backend_id);
|
|
}
|
|
}
|
|
}
|
|
|
|
// pass 3: upgrade nodes to higher prio backends with compatible buffer types
|
|
// if the tensor is already in the same buffer type (*) as another higher priority backend, we should move it there
|
|
// however, we also need to verify that the sources are in compatible buffer types
|
|
// (*) 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
|
|
// however, this is slow to verify, so we have a more strict requirement that the buffer type is the same
|
|
// this is not uncommon since multiple backends can use host memory, with the same buffer type (eg. BLAS and CPU)
|
|
// additionally, set remaining unassigned nodes to the backend with the most supported inputs
|
|
// only nodes that could not be assigned during expansion due to the backend not supporting the op should be unassigned at this point
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
int * node_backend_id = &tensor_backend_id(node);
|
|
if (*node_backend_id == -1) {
|
|
// unassigned node: find the backend with the most supported inputs
|
|
int n_supported_best = -1;
|
|
for (int b = 0; b < sched->n_backends; b++) {
|
|
if (ggml_backend_supports_op(sched->backends[b], node)) {
|
|
int n_supported = 0;
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
if ((tensor_backend_id(src) != -1 || tensor_backend_id(src->view_src) != -1) && ggml_backend_sched_buffer_supported(sched, src, b)) {
|
|
n_supported++;
|
|
}
|
|
}
|
|
if (n_supported > n_supported_best) {
|
|
n_supported_best = n_supported;
|
|
*node_backend_id = b;
|
|
SET_CAUSE(node, "3.best");
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
// assigned node: upgrade to higher prio backend if possible
|
|
for (int b = 0; b < *node_backend_id; b++) {
|
|
if (sched->bufts[b] == sched->bufts[*node_backend_id] && ggml_backend_supports_op(sched->backends[b], node)) {
|
|
bool supported = true;
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
if (!ggml_backend_sched_buffer_supported(sched, src, b)) {
|
|
supported = false;
|
|
break;
|
|
}
|
|
}
|
|
if (supported) {
|
|
*node_backend_id = b;
|
|
SET_CAUSE(node, "3.upg");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// pass 4: assign backends to remaining src from dst and view_src
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
int * cur_backend_id = &tensor_backend_id(node);
|
|
if (node->view_src != NULL && *cur_backend_id == -1) {
|
|
*cur_backend_id = tensor_backend_id(node->view_src);
|
|
SET_CAUSE(node, "4.vsrc");
|
|
}
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
int * src_backend_id = &tensor_backend_id(src);
|
|
if (*src_backend_id == -1) {
|
|
if (src->view_src != NULL) {
|
|
// views are always on the same backend as the source
|
|
*src_backend_id = tensor_backend_id(src->view_src);
|
|
SET_CAUSE(src, "4.vsrc");
|
|
} else {
|
|
*src_backend_id = *cur_backend_id;
|
|
SET_CAUSE(src, "4.cur");
|
|
}
|
|
}
|
|
}
|
|
// if the node is still unassigned, assign it to the first backend that supports it
|
|
for (int b = 0; b < sched->n_backends && *cur_backend_id == -1; b++) {
|
|
ggml_backend_sched_set_if_supported(sched, node, b, cur_backend_id);
|
|
}
|
|
GGML_ASSERT(*cur_backend_id != -1);
|
|
}
|
|
|
|
// pass 5: split graph, find tensors that need to be copied
|
|
{
|
|
int i_split = 0;
|
|
struct ggml_backend_sched_split * split = &sched->splits[0];
|
|
// find the backend of the first split, skipping view ops
|
|
int i = 0;
|
|
for (; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
if (!ggml_is_view_op(node->op)) {
|
|
split->backend_id = tensor_backend_id(node);
|
|
break;
|
|
}
|
|
}
|
|
split->i_start = 0;
|
|
split->n_inputs = 0;
|
|
int cur_backend_id = split->backend_id;
|
|
bool split_has_nodes = false;
|
|
for (; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
|
|
if (ggml_is_view_op(node->op)) {
|
|
continue;
|
|
}
|
|
|
|
const int node_backend_id = tensor_backend_id(node);
|
|
|
|
GGML_ASSERT(node_backend_id != -1); // all nodes should be assigned by now, this can happen if there is no CPU fallback
|
|
|
|
// check if we should start a new split based on the sources of the current node
|
|
// this also applies to a split without inputs, e.g. one that follows a split that only writes to a host buffer
|
|
bool need_new_split = false;
|
|
if (node_backend_id == cur_backend_id && split_has_nodes) {
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
// check if a weight is on a different and incompatible backend
|
|
// by starting a new split, the memory of the previously offloaded weights can be reused
|
|
if (src->buffer != NULL && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS) {
|
|
int src_backend_id = tensor_backend_id(src);
|
|
if (src_backend_id != cur_backend_id && !ggml_backend_sched_buffer_supported(sched, src, cur_backend_id)) {
|
|
need_new_split = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (node_backend_id != cur_backend_id || need_new_split) {
|
|
split->i_end = i;
|
|
i_split++;
|
|
if (i_split >= sched->splits_capacity) {
|
|
int old_cap = sched->splits_capacity;
|
|
sched->splits_capacity *= 2;
|
|
sched->splits = (ggml_backend_sched_split *)
|
|
realloc(sched->splits, sched->splits_capacity * sizeof(struct ggml_backend_sched_split));
|
|
GGML_ASSERT(sched->splits != NULL);
|
|
for (int k = old_cap; k < sched->splits_capacity; k++) {
|
|
memset(&sched->splits[k], 0, sizeof(struct ggml_backend_sched_split));
|
|
}
|
|
}
|
|
split = &sched->splits[i_split];
|
|
split->backend_id = node_backend_id;
|
|
split->i_start = i;
|
|
split->n_inputs = 0;
|
|
cur_backend_id = node_backend_id;
|
|
}
|
|
split_has_nodes = true;
|
|
|
|
// find inputs that are not on the same backend
|
|
for (int j = 0; j < GGML_MAX_SRC; j++) {
|
|
struct ggml_tensor * src = node->src[j];
|
|
if (src == NULL) {
|
|
continue;
|
|
}
|
|
|
|
size_t src_id = hash_id(src);
|
|
const int src_backend_id = sched->hv_tensor_backend_ids[src_id];
|
|
GGML_ASSERT(src_backend_id != -1); // all inputs should be assigned by now
|
|
|
|
if (src_backend_id != cur_backend_id && !ggml_backend_sched_buffer_supported(sched, src, cur_backend_id)) {
|
|
// create a copy of the input in the split's backend
|
|
if (tensor_id_copy(src_id, cur_backend_id, 0) == NULL) {
|
|
ggml_backend_t backend = sched->backends[cur_backend_id];
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
struct ggml_tensor * tensor_copy = ggml_dup_tensor_layout(sched->ctx, src);
|
|
ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), src->name, c);
|
|
if (sched->n_copies > 1) {
|
|
ggml_set_input(tensor_copy);
|
|
ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor
|
|
}
|
|
tensor_id_copy(src_id, cur_backend_id, c) = tensor_copy;
|
|
SET_CAUSE(tensor_copy, "4.cpy");
|
|
}
|
|
int n_inputs = split->n_inputs++;
|
|
if (n_inputs >= split->inputs_capacity) {
|
|
ggml_backend_sched_split_inputs_grow(split);
|
|
}
|
|
split->inputs[n_inputs] = src;
|
|
}
|
|
// inputs of nodes that are not computed (e.g. the unselected branches of ggml_build_forward_select)
|
|
// stay in the split so that the allocation does not change, but they do not need to be copied
|
|
if (node->flags & GGML_TENSOR_FLAG_COMPUTE) {
|
|
sched->hv_tensor_requires_copy[src_id] = true;
|
|
}
|
|
node->src[j] = tensor_id_copy(src_id, cur_backend_id, sched->cur_copy);
|
|
}
|
|
}
|
|
}
|
|
split->i_end = graph->n_nodes;
|
|
sched->n_splits = i_split + 1;
|
|
}
|
|
|
|
if (sched->debug) {
|
|
ggml_backend_sched_print_assignments(sched, graph);
|
|
}
|
|
|
|
// pass 6: collect all input tensors into graph_inputs
|
|
// this includes inputs not consumed by any node (e.g. the embeddings input of a text-only batch) so that
|
|
// the graph composition does not depend on which inputs are used, which would otherwise cause graph
|
|
// reallocations when switching between different types of batches [GGML_SCHED_DEBUG_REALLOC]
|
|
if (sched->n_copies > 1) {
|
|
for (int i = 0; i < graph->n_leafs; i++) {
|
|
struct ggml_tensor * leaf = graph->leafs[i];
|
|
if ((leaf->flags & GGML_TENSOR_FLAG_INPUT) == 0) {
|
|
continue;
|
|
}
|
|
|
|
const size_t leaf_id = hash_id(leaf);
|
|
const int leaf_backend_id = tensor_backend_id(leaf);
|
|
GGML_ASSERT(leaf_backend_id != -1); // all leafs should be assigned by now
|
|
|
|
if (tensor_id_copy(leaf_id, leaf_backend_id, 0) == NULL) {
|
|
ggml_backend_t backend = sched->backends[leaf_backend_id];
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
struct ggml_tensor * tensor_copy;
|
|
if (c == sched->cur_copy) {
|
|
tensor_copy = leaf; // use the original tensor as the current copy
|
|
} else {
|
|
tensor_copy = ggml_dup_tensor_layout(sched->ctx, leaf);
|
|
ggml_format_name(tensor_copy, "%s#%s#%d", ggml_backend_name(backend), leaf->name, c);
|
|
}
|
|
ggml_set_input(tensor_copy);
|
|
ggml_set_output(tensor_copy); // prevent ggml-alloc from overwriting the tensor
|
|
tensor_id_copy(leaf_id, leaf_backend_id, c) = tensor_copy;
|
|
SET_CAUSE(tensor_copy, "6.cpy");
|
|
}
|
|
}
|
|
|
|
int n_graph_inputs = sched->n_graph_inputs++;
|
|
if (n_graph_inputs >= sched->graph_inputs_capacity) {
|
|
ggml_backend_sched_graph_inputs_grow(sched);
|
|
}
|
|
sched->graph_inputs[n_graph_inputs] = leaf;
|
|
}
|
|
}
|
|
|
|
// swap node_backend_ids and leaf _backend_ids with prevs
|
|
{
|
|
int * tmp = sched->node_backend_ids;
|
|
sched->node_backend_ids = sched->prev_node_backend_ids;
|
|
sched->prev_node_backend_ids = tmp;
|
|
|
|
tmp = sched->leaf_backend_ids;
|
|
sched->leaf_backend_ids = sched->prev_leaf_backend_ids;
|
|
sched->prev_leaf_backend_ids = tmp;
|
|
}
|
|
|
|
// optimize the split graphs and collect the allocation dependencies added by the backends
|
|
// this needs to happen before we make graph_copy, so they are in sync
|
|
// TODO: this may create many small allocations in the scheduler, restructure to use a flat array
|
|
std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> alloc_deps;
|
|
|
|
struct ggml_backend_graph_optimize_params opt_params = {
|
|
/* .add_alloc_dep = */ [](void * user_data, ggml_tensor * tensor, ggml_tensor * until) {
|
|
auto & deps = *(std::unordered_map<ggml_tensor *, std::vector<ggml_tensor *>> *) user_data;
|
|
std::vector<ggml_tensor *> & keep = deps[until];
|
|
if (std::find(keep.begin(), keep.end(), tensor) == keep.end()) {
|
|
keep.push_back(tensor);
|
|
}
|
|
},
|
|
/* .user_data = */ &alloc_deps,
|
|
};
|
|
|
|
for (int i = 0; i < sched->n_splits; i++) {
|
|
struct ggml_backend_sched_split * split = &sched->splits[i];
|
|
split->graph = ggml_graph_view(graph, split->i_start, split->i_end);
|
|
|
|
ggml_backend_graph_optimize(sched->backends[split->backend_id], &split->graph, &opt_params);
|
|
}
|
|
|
|
// each dep is added to graph_copy as a GGML_OP_NONE node with the kept tensors as srcs
|
|
int n_dep_nodes = 0;
|
|
for (const auto & it : alloc_deps) {
|
|
n_dep_nodes += (it.second.size() + GGML_MAX_SRC - 1) / GGML_MAX_SRC;
|
|
}
|
|
|
|
int total_inputs = sched->n_graph_inputs;
|
|
for (int i = 0; i < sched->n_splits; i++) {
|
|
total_inputs += sched->splits[i].n_inputs;
|
|
}
|
|
int graph_size = std::max(graph->n_nodes, graph->n_leafs) + total_inputs * 2 * sched->n_copies + n_dep_nodes;
|
|
|
|
// remember the actual graph_size for performing reallocation checks later
|
|
sched->prev_graph_size = sched->graph_size;
|
|
sched->graph_size = graph_size;
|
|
|
|
if (sched->graph.size < graph_size) {
|
|
sched->graph.size = graph_size;
|
|
sched->graph.nodes = (ggml_tensor **) realloc(sched->graph.nodes, graph_size * sizeof(struct ggml_tensor *));
|
|
sched->graph.leafs = (ggml_tensor **) realloc(sched->graph.leafs, graph_size * sizeof(struct ggml_tensor *));
|
|
GGML_ASSERT(sched->graph.nodes != NULL);
|
|
GGML_ASSERT(sched->graph.leafs != NULL);
|
|
}
|
|
sched->graph.n_nodes = 0;
|
|
sched->graph.n_leafs = 0;
|
|
|
|
struct ggml_cgraph * graph_copy = &sched->graph;
|
|
|
|
int n_dep_nodes_added = 0;
|
|
|
|
for (int i = 0; i < sched->n_splits; i++) {
|
|
struct ggml_backend_sched_split * split = &sched->splits[i];
|
|
|
|
// add inputs to the graph copy so that they are allocated by ggml-alloc at the start of the split
|
|
for (int j = 0; j < split->n_inputs; j++) {
|
|
assert(graph_copy->size > (graph_copy->n_nodes + 1));
|
|
|
|
struct ggml_tensor * input = split->inputs[j];
|
|
const size_t input_id = hash_id(input);
|
|
struct ggml_tensor * input_cpy = tensor_id_copy(input_id, split->backend_id, sched->cur_copy);
|
|
|
|
// add a dependency to the input source so that it is not freed before the copy is done
|
|
struct ggml_tensor * input_dep = ggml_view_tensor(sched->ctx, input);
|
|
input_dep->src[0] = input;
|
|
sched->node_backend_ids[graph_copy->n_nodes] = sched->hv_tensor_backend_ids[input_id];
|
|
graph_copy->nodes[graph_copy->n_nodes++] = input_dep;
|
|
|
|
// add a dependency to the input copy so that it is allocated at the start of the split
|
|
sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
|
|
graph_copy->nodes[graph_copy->n_nodes++] = input_cpy;
|
|
}
|
|
|
|
for (int j = split->i_start; j < split->i_end; j++) {
|
|
assert(graph_copy->size > graph_copy->n_nodes);
|
|
sched->node_backend_ids[graph_copy->n_nodes] = tensor_backend_id(graph->nodes[j]);
|
|
graph_copy->nodes[graph_copy->n_nodes++] = graph->nodes[j];
|
|
|
|
if (alloc_deps.empty()) {
|
|
continue;
|
|
}
|
|
|
|
// add a dependency node so that the kept tensors are not freed before this node is computed
|
|
auto it = alloc_deps.find(graph->nodes[j]);
|
|
if (it != alloc_deps.end()) {
|
|
const std::vector<ggml_tensor *> & keep = it->second;
|
|
for (size_t k = 0; k < keep.size(); k += GGML_MAX_SRC) {
|
|
struct ggml_tensor * dep = ggml_view_tensor(sched->ctx, keep[k]);
|
|
for (size_t s = 0; s < GGML_MAX_SRC && k + s < keep.size(); s++) {
|
|
dep->src[s] = keep[k + s];
|
|
}
|
|
assert(graph_copy->size > graph_copy->n_nodes);
|
|
sched->node_backend_ids[graph_copy->n_nodes] = split->backend_id;
|
|
graph_copy->nodes[graph_copy->n_nodes++] = dep;
|
|
n_dep_nodes_added++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// a mismatch means a backend added a dep with an `until` tensor that is not a node of the optimized graph
|
|
GGML_ASSERT(n_dep_nodes_added == n_dep_nodes);
|
|
|
|
if (sched->n_copies > 1) {
|
|
// add input copies as leafs so that they are allocated first
|
|
for (int i = 0; i < sched->n_graph_inputs; i++) {
|
|
struct ggml_tensor * input = sched->graph_inputs[i];
|
|
size_t id = hash_id(input);
|
|
int backend_id = tensor_backend_id(input);
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c);
|
|
sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id;
|
|
assert(graph_copy->size > graph_copy->n_leafs);
|
|
graph_copy->leafs[graph_copy->n_leafs++] = input_cpy;
|
|
}
|
|
}
|
|
|
|
for (int i = 0; i < sched->n_splits; i++) {
|
|
struct ggml_backend_sched_split * split = &sched->splits[i];
|
|
int backend_id = split->backend_id;
|
|
for (int j = 0; j < split->n_inputs; j++) {
|
|
struct ggml_tensor * input = split->inputs[j];
|
|
size_t id = hash_id(input);
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
struct ggml_tensor * input_cpy = tensor_id_copy(id, backend_id, c);
|
|
sched->leaf_backend_ids[graph_copy->n_leafs] = backend_id;
|
|
assert(graph_copy->size > graph_copy->n_leafs);
|
|
graph_copy->leafs[graph_copy->n_leafs++] = input_cpy;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// add leafs from the original graph
|
|
for (int i = 0; i < graph->n_leafs; i++) {
|
|
struct ggml_tensor * leaf = graph->leafs[i];
|
|
sched->leaf_backend_ids[graph_copy->n_leafs] = tensor_backend_id(leaf);
|
|
assert(graph_copy->size > graph_copy->n_leafs);
|
|
graph_copy->leafs[graph_copy->n_leafs++] = leaf;
|
|
}
|
|
|
|
// set ids for all splits
|
|
for (int i = 0; i < sched->n_splits; ++i) {
|
|
sched->splits[i].graph.uid = ggml_graph_next_uid();
|
|
}
|
|
}
|
|
|
|
static bool ggml_backend_sched_alloc_splits(ggml_backend_sched_t sched) {
|
|
bool backend_ids_changed = false;
|
|
for (int i = 0; i < sched->graph.n_nodes; i++) {
|
|
if (sched->node_backend_ids[i] != sched->prev_node_backend_ids[i] &&
|
|
sched->bufts[sched->node_backend_ids[i]] != sched->bufts[sched->prev_node_backend_ids[i]]) {
|
|
backend_ids_changed = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!backend_ids_changed) {
|
|
for (int i = 0; i < sched->graph.n_leafs; i++) {
|
|
if (sched->leaf_backend_ids[i] != sched->prev_leaf_backend_ids[i] &&
|
|
sched->bufts[sched->leaf_backend_ids[i]] != sched->bufts[sched->prev_leaf_backend_ids[i]]) {
|
|
backend_ids_changed = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// allocate graph
|
|
if (backend_ids_changed || !ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) {
|
|
#ifndef NDEBUG
|
|
GGML_LOG_DEBUG("%s: failed to allocate graph, reserving (backend_ids_changed = %d)\n", __func__, backend_ids_changed);
|
|
#endif
|
|
|
|
// a reallocation with an unchanged graph size means that the previous reservation was not sufficient
|
|
const bool graph_size_changed = sched->prev_graph_size != sched->graph_size;
|
|
|
|
if (sched->callback_realloc != NULL) {
|
|
sched->callback_realloc(sched, &sched->graph, backend_ids_changed, graph_size_changed, sched->callback_realloc_user_data);
|
|
}
|
|
|
|
if (sched->debug_realloc > 0) {
|
|
// we are interested only in situations where the graph was reallocated even though its size remained the same [GGML_SCHED_DEBUG_REALLOC]
|
|
// example: https://github.com/ggml-org/llama.cpp/pull/17143
|
|
const bool unexpected = !backend_ids_changed && !graph_size_changed;
|
|
|
|
if (unexpected || sched->debug_realloc > 1) {
|
|
GGML_ABORT("%s: unexpected graph reallocation (graph size = %d, nodes = %d, leafs = %d), debug_realloc = %d\n", __func__,
|
|
sched->graph_size, sched->graph.n_nodes, sched->graph.n_leafs, sched->debug_realloc);
|
|
}
|
|
}
|
|
|
|
// the re-allocation may cause the split inputs to be moved to a different address
|
|
// synchronize without ggml_backend_sched_synchronize to avoid changing cur_copy
|
|
for (int i = 0; i < sched->n_backends; i++) {
|
|
ggml_backend_synchronize(sched->backends[i]);
|
|
}
|
|
|
|
if (!ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids)) {
|
|
GGML_LOG_ERROR("%s: failed to reserve graph buffers\n", __func__);
|
|
return false;
|
|
}
|
|
if (!ggml_gallocr_alloc_graph(sched->galloc, &sched->graph)) {
|
|
GGML_LOG_ERROR("%s: failed to allocate graph\n", __func__);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
static bool ggml_backend_sched_is_host_weight(const struct ggml_tensor * t) {
|
|
return t->buffer != NULL &&
|
|
ggml_backend_buffer_get_usage(t->buffer) == GGML_BACKEND_BUFFER_USAGE_WEIGHTS &&
|
|
ggml_backend_buffer_is_host(t->buffer);
|
|
}
|
|
|
|
static void ggml_backend_sched_copy_input(ggml_backend_sched_t sched, struct ggml_backend_sched_split * split, struct ggml_tensor * input) {
|
|
const int split_backend_id = split->backend_id;
|
|
ggml_backend_t split_backend = sched->backends[split_backend_id];
|
|
ggml_backend_t input_backend = ggml_backend_sched_get_tensor_backend(sched, input);
|
|
struct ggml_tensor * input_cpy = tensor_copy(input, split_backend_id, sched->cur_copy);
|
|
|
|
// read before the previous split, wait for the copy only
|
|
if (split == &sched->splits[sched->prefetch_split]) {
|
|
for (int i = 0; i < sched->n_prefetched; i++) {
|
|
if (sched->prefetched[i] == input) {
|
|
ggml_backend_event_synchronize(sched->prefetch_events[sched->prefetch_backend_id]);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (input->flags & GGML_TENSOR_FLAG_INPUT) {
|
|
// inputs from the user must be copied immediately to prevent the user overwriting the data before the copy is done
|
|
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
|
|
ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]);
|
|
} else {
|
|
ggml_backend_synchronize(split_backend);
|
|
}
|
|
ggml_backend_tensor_copy(input, input_cpy);
|
|
return;
|
|
}
|
|
|
|
// wait for the split backend to finish using the input before overwriting it
|
|
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
|
|
ggml_backend_event_wait(split_backend, sched->events[split_backend_id][sched->cur_copy]);
|
|
} else {
|
|
ggml_backend_synchronize(split_backend);
|
|
}
|
|
|
|
if (sched->callback_copy != NULL && ggml_backend_sched_is_host_weight(input) &&
|
|
sched->callback_copy(split_backend, input, input_cpy, &split->graph, sched->callback_copy_user_data)) {
|
|
return;
|
|
}
|
|
|
|
// 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
|
|
// TODO: add public function to facilitate this, since applications do not have direct access to the backend interface
|
|
if (!split_backend->iface.cpy_tensor_async || !split_backend->iface.cpy_tensor_async(input_backend, split_backend, input, input_cpy)) {
|
|
ggml_backend_synchronize(input_backend);
|
|
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
|
|
ggml_backend_event_synchronize(sched->events[split_backend_id][sched->cur_copy]);
|
|
} else {
|
|
ggml_backend_synchronize(split_backend);
|
|
}
|
|
ggml_backend_tensor_copy(input, input_cpy);
|
|
}
|
|
}
|
|
|
|
// the inputs of the next split that are computed on the backend of this split before it, and copied to host memory,
|
|
// are copied before this split computes, so that the next split waits for these copies instead of this split
|
|
// e.g. a CPU split runs while a GPU split computes, if it reads only the results of the earlier splits
|
|
static void ggml_backend_sched_prefetch_inputs(ggml_backend_sched_t sched, int split_id) {
|
|
sched->n_prefetched = 0;
|
|
if (split_id + 1 >= sched->n_splits) {
|
|
return;
|
|
}
|
|
struct ggml_backend_sched_split * split = &sched->splits[split_id];
|
|
struct ggml_backend_sched_split * next = &sched->splits[split_id + 1];
|
|
const int backend_id = split->backend_id;
|
|
ggml_backend_t backend = sched->backends[backend_id];
|
|
if (backend->iface.get_tensor_async == NULL) {
|
|
return;
|
|
}
|
|
|
|
for (int i = 0; i < next->n_inputs && sched->n_prefetched < GGML_SCHED_MAX_SPLIT_INPUTS; i++) {
|
|
struct ggml_tensor * input = next->inputs[i];
|
|
if ((input->flags & GGML_TENSOR_FLAG_INPUT) || tensor_backend_id(input) != backend_id) {
|
|
continue;
|
|
}
|
|
struct ggml_tensor * input_cpy = tensor_copy(input, next->backend_id, sched->cur_copy);
|
|
if (input_cpy->buffer == NULL || !ggml_backend_buffer_is_host(input_cpy->buffer)) {
|
|
continue;
|
|
}
|
|
|
|
// only results of earlier splits, the copy callback of this split runs later and can write other tensors (e.g. the MoE cache)
|
|
const struct ggml_tensor * base = input->view_src ? input->view_src : input;
|
|
if (base->buffer == NULL || ggml_backend_buffer_get_usage(base->buffer) != GGML_BACKEND_BUFFER_USAGE_COMPUTE) {
|
|
continue;
|
|
}
|
|
|
|
// not if this split computes or writes the input
|
|
bool written = false;
|
|
for (int j = 0; j < split->graph.n_nodes && !written; j++) {
|
|
const struct ggml_tensor * node = split->graph.nodes[j];
|
|
written = !ggml_is_view_op(node->op) && (node == base || node->view_src == base);
|
|
}
|
|
if (written) {
|
|
continue;
|
|
}
|
|
|
|
if (!sched->prefetch_tried[backend_id]) {
|
|
sched->prefetch_tried[backend_id] = true;
|
|
sched->prefetch_events[backend_id] = ggml_backend_event_new(backend->device);
|
|
}
|
|
if (sched->prefetch_events[backend_id] == NULL) {
|
|
return;
|
|
}
|
|
|
|
ggml_backend_tensor_get_async(backend, input, input_cpy->data, 0, ggml_nbytes(input));
|
|
sched->prefetched[sched->n_prefetched++] = input;
|
|
}
|
|
|
|
if (sched->n_prefetched > 0) {
|
|
sched->prefetch_split = split_id + 1;
|
|
sched->prefetch_backend_id = backend_id;
|
|
ggml_backend_event_record(sched->prefetch_events[backend_id], backend);
|
|
}
|
|
}
|
|
|
|
static enum ggml_status ggml_backend_sched_compute_splits(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
struct ggml_backend_sched_split * splits = sched->splits;
|
|
|
|
int prev_backend_id = -1;
|
|
|
|
for (int split_id = 0; split_id < sched->n_splits; split_id++) {
|
|
struct ggml_backend_sched_split * split = &splits[split_id];
|
|
int split_backend_id = split->backend_id;
|
|
ggml_backend_t split_backend = sched->backends[split_backend_id];
|
|
|
|
// ensure the previous split's async work has completed before we start
|
|
// this split, the allocator may have reused buffer regions across splits
|
|
if (split->n_inputs == 0 && prev_backend_id >= 0 && prev_backend_id != split_backend_id) {
|
|
if (sched->events[prev_backend_id][sched->cur_copy] != NULL) {
|
|
ggml_backend_event_synchronize(sched->events[prev_backend_id][sched->cur_copy]);
|
|
} else {
|
|
ggml_backend_synchronize(sched->backends[prev_backend_id]);
|
|
}
|
|
}
|
|
|
|
// copy the input tensors to the split backend
|
|
// the weights in host memory are copied last, so that the copy callback can read the other inputs of the split
|
|
for (int input_id = 0; input_id < split->n_inputs; input_id++) {
|
|
struct ggml_tensor * input = split->inputs[input_id];
|
|
if (!ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) {
|
|
ggml_backend_sched_copy_input(sched, split, input);
|
|
}
|
|
}
|
|
// after the copies above, which may read host memory reused by the copies of the next split
|
|
// before the weights, whose copy callback may queue large uploads
|
|
ggml_backend_sched_prefetch_inputs(sched, split_id);
|
|
for (int input_id = 0; input_id < split->n_inputs; input_id++) {
|
|
struct ggml_tensor * input = split->inputs[input_id];
|
|
if (ggml_backend_sched_is_host_weight(input) && sched->hv_tensor_requires_copy[hash_id(input)]) {
|
|
ggml_backend_sched_copy_input(sched, split, input);
|
|
}
|
|
}
|
|
|
|
if (!sched->callback_eval) {
|
|
enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &split->graph);
|
|
if (ec != GGML_STATUS_SUCCESS) {
|
|
return ec;
|
|
}
|
|
} else {
|
|
// similar to ggml_backend_compare_graph_backend
|
|
for (int j0 = 0; j0 < split->graph.n_nodes; j0++) {
|
|
struct ggml_tensor * t = split->graph.nodes[j0];
|
|
|
|
// check if the user needs data from this node
|
|
bool need = sched->callback_eval(t, true, sched->callback_eval_user_data);
|
|
|
|
int j1 = j0;
|
|
|
|
// determine the range [j0, j1] of nodes that can be computed together
|
|
while (!need && j1 < split->graph.n_nodes - 1) {
|
|
t = split->graph.nodes[++j1];
|
|
need = sched->callback_eval(t, true, sched->callback_eval_user_data);
|
|
}
|
|
|
|
struct ggml_cgraph gv = ggml_graph_view(&split->graph, j0, j1 + 1);
|
|
|
|
enum ggml_status ec = ggml_backend_graph_compute_async(split_backend, &gv);
|
|
if (ec != GGML_STATUS_SUCCESS) {
|
|
return ec;
|
|
}
|
|
|
|
// TODO: pass backend to the callback, then the user can decide if they want to synchronize
|
|
ggml_backend_synchronize(split_backend);
|
|
|
|
if (need && !sched->callback_eval(t, false, sched->callback_eval_user_data)) {
|
|
break;
|
|
}
|
|
|
|
j0 = j1;
|
|
}
|
|
}
|
|
|
|
// record the event of this split
|
|
if (sched->events[split_backend_id][sched->cur_copy] != NULL) {
|
|
ggml_backend_event_record(sched->events[split_backend_id][sched->cur_copy], split_backend);
|
|
}
|
|
|
|
prev_backend_id = split_backend_id;
|
|
}
|
|
|
|
return GGML_STATUS_SUCCESS;
|
|
}
|
|
|
|
ggml_backend_sched_t ggml_backend_sched_new(
|
|
ggml_backend_t * backends,
|
|
ggml_backend_buffer_type_t * bufts,
|
|
int n_backends,
|
|
size_t graph_size,
|
|
bool parallel,
|
|
bool op_offload) {
|
|
GGML_ASSERT(n_backends > 0);
|
|
GGML_ASSERT(n_backends <= GGML_SCHED_MAX_BACKENDS);
|
|
GGML_ASSERT(ggml_backend_dev_type(ggml_backend_get_device(backends[n_backends - 1])) == GGML_BACKEND_DEVICE_TYPE_CPU);
|
|
|
|
struct ggml_backend_sched * sched = (ggml_backend_sched *) calloc(1, sizeof(struct ggml_backend_sched));
|
|
|
|
const char * GGML_SCHED_DEBUG = getenv("GGML_SCHED_DEBUG");
|
|
sched->debug = GGML_SCHED_DEBUG ? atoi(GGML_SCHED_DEBUG) : 0;
|
|
|
|
sched->debug_realloc = 0;
|
|
#ifdef GGML_SCHED_NO_REALLOC
|
|
sched->debug_realloc = 1;
|
|
#endif
|
|
const char * GGML_SCHED_DEBUG_REALLOC = getenv("GGML_SCHED_DEBUG_REALLOC");
|
|
sched->debug_realloc = GGML_SCHED_DEBUG_REALLOC ? atoi(GGML_SCHED_DEBUG_REALLOC) : sched->debug_realloc;
|
|
|
|
sched->n_backends = n_backends;
|
|
sched->n_copies = parallel ? GGML_SCHED_MAX_COPIES : 1;
|
|
|
|
// initialize hash table
|
|
// FIXME: needs to be size*2 to account for leafs (do it in graph_split instead)
|
|
sched->hash_set = ggml_hash_set_new(graph_size);
|
|
sched->hv_tensor_backend_ids = (int *) malloc(sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0]));
|
|
sched->hv_tensor_copies = (ggml_tensor **) malloc(sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *));
|
|
sched->hv_tensor_requires_copy = (bool *) malloc(sched->hash_set.size * sizeof(sched->hv_tensor_requires_copy[0]));
|
|
|
|
const size_t ggml_sched_max_splits = graph_size; // at most there is one split for each node in the graph
|
|
const size_t nodes_size = graph_size + ggml_sched_max_splits*GGML_SCHED_MAX_SPLIT_INPUTS*2;
|
|
sched->node_backend_ids = (int *) calloc(nodes_size, sizeof(sched->node_backend_ids[0]));
|
|
sched->leaf_backend_ids = (int *) calloc(nodes_size, sizeof(sched->leaf_backend_ids[0]));
|
|
sched->prev_node_backend_ids = (int *) calloc(nodes_size, sizeof(sched->prev_node_backend_ids[0]));
|
|
sched->prev_leaf_backend_ids = (int *) calloc(nodes_size, sizeof(sched->prev_leaf_backend_ids[0]));
|
|
|
|
sched->graph_size = 0;
|
|
sched->prev_graph_size = 0;
|
|
|
|
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);
|
|
sched->context_buffer = (char *) malloc(sched->context_buffer_size);
|
|
|
|
const int initial_splits_capacity = 16;
|
|
sched->splits = (ggml_backend_sched_split *) calloc(initial_splits_capacity, sizeof(sched->splits[0]));
|
|
sched->splits_capacity = initial_splits_capacity;
|
|
|
|
sched->graph_inputs_capacity = GGML_SCHED_MAX_SPLIT_INPUTS;
|
|
sched->graph_inputs = (struct ggml_tensor **) calloc(sched->graph_inputs_capacity, sizeof(struct ggml_tensor *));
|
|
|
|
for (int b = 0; b < n_backends; b++) {
|
|
sched->backends[b] = backends[b];
|
|
sched->bufts[b] = bufts ? bufts[b] : ggml_backend_get_default_buffer_type(backends[b]);
|
|
GGML_ASSERT(ggml_backend_supports_buft(backends[b], sched->bufts[b]));
|
|
|
|
if (sched->n_copies > 1) {
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
sched->events[b][c] = ggml_backend_event_new(backends[b]->device);
|
|
}
|
|
}
|
|
}
|
|
|
|
sched->galloc = ggml_gallocr_new_n(sched->bufts, n_backends);
|
|
sched->op_offload = op_offload;
|
|
|
|
ggml_backend_sched_reset(sched);
|
|
|
|
return sched;
|
|
}
|
|
|
|
void ggml_backend_sched_free(ggml_backend_sched_t sched) {
|
|
if (sched == NULL) {
|
|
return;
|
|
}
|
|
for (int b = 0; b < sched->n_backends; b++) {
|
|
for (int c = 0; c < sched->n_copies; c++) {
|
|
ggml_backend_event_free(sched->events[b][c]);
|
|
}
|
|
ggml_backend_event_free(sched->prefetch_events[b]);
|
|
}
|
|
ggml_gallocr_free(sched->galloc);
|
|
ggml_free(sched->ctx);
|
|
ggml_hash_set_free(&sched->hash_set);
|
|
for (int i = 0; i < sched->splits_capacity; i++) {
|
|
free(sched->splits[i].inputs);
|
|
}
|
|
free(sched->splits);
|
|
free(sched->graph_inputs);
|
|
free(sched->hv_tensor_backend_ids);
|
|
free(sched->hv_tensor_copies);
|
|
free(sched->hv_tensor_requires_copy);
|
|
free(sched->node_backend_ids);
|
|
free(sched->leaf_backend_ids);
|
|
free(sched->prev_node_backend_ids);
|
|
free(sched->prev_leaf_backend_ids);
|
|
free(sched->context_buffer);
|
|
free(sched->graph.nodes);
|
|
free(sched->graph.leafs);
|
|
free(sched);
|
|
}
|
|
|
|
void ggml_backend_sched_reset(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
// reset state for the next run
|
|
if (!sched->is_reset) {
|
|
ggml_hash_set_reset(&sched->hash_set);
|
|
memset(sched->hv_tensor_backend_ids, -1, sched->hash_set.size * sizeof(sched->hv_tensor_backend_ids[0]));
|
|
memset(sched->hv_tensor_copies, 0, sched->hash_set.size * sched->n_backends * sched->n_copies * sizeof(struct ggml_tensor *));
|
|
memset(sched->hv_tensor_requires_copy, 0, sched->hash_set.size * sizeof(sched->hv_tensor_requires_copy[0]));
|
|
sched->is_reset = true;
|
|
}
|
|
sched->is_alloc = false;
|
|
}
|
|
|
|
void ggml_backend_sched_reserve_size(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph, size_t * sizes) {
|
|
GGML_ASSERT(sched);
|
|
GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs);
|
|
GGML_ASSERT(sizes);
|
|
|
|
ggml_backend_sched_reset(sched);
|
|
|
|
ggml_backend_sched_synchronize(sched);
|
|
|
|
ggml_backend_sched_split_graph(sched, measure_graph);
|
|
|
|
ggml_gallocr_reserve_n_size(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids, sizes);
|
|
}
|
|
|
|
bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph) {
|
|
GGML_ASSERT(sched);
|
|
GGML_ASSERT((int)sched->hash_set.size >= measure_graph->n_nodes + measure_graph->n_leafs);
|
|
|
|
ggml_backend_sched_synchronize(sched);
|
|
|
|
ggml_backend_sched_split_graph(sched, measure_graph);
|
|
|
|
if (!ggml_gallocr_reserve_n(sched->galloc, &sched->graph, sched->node_backend_ids, sched->leaf_backend_ids)) {
|
|
return false;
|
|
}
|
|
|
|
ggml_backend_sched_reset(sched);
|
|
|
|
return true;
|
|
}
|
|
|
|
bool ggml_backend_sched_alloc_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
|
|
GGML_ASSERT(sched);
|
|
GGML_ASSERT((int)sched->hash_set.size >= graph->n_nodes + graph->n_leafs);
|
|
GGML_ASSERT(!sched->is_alloc);
|
|
|
|
sched->cur_copy = sched->next_copy;
|
|
sched->next_copy = (sched->next_copy + 1) % sched->n_copies;
|
|
|
|
ggml_backend_sched_split_graph(sched, graph);
|
|
|
|
if (!ggml_backend_sched_alloc_splits(sched)) {
|
|
return false;
|
|
}
|
|
|
|
sched->is_alloc = true;
|
|
|
|
return true;
|
|
}
|
|
|
|
enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
|
|
enum ggml_status err = ggml_backend_sched_graph_compute_async(sched, graph);
|
|
ggml_backend_sched_synchronize(sched);
|
|
return err;
|
|
}
|
|
|
|
enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph) {
|
|
GGML_ASSERT(sched);
|
|
if (!sched->is_reset && !sched->is_alloc) {
|
|
ggml_backend_sched_reset(sched);
|
|
}
|
|
|
|
if (!sched->is_alloc) {
|
|
if (!ggml_backend_sched_alloc_graph(sched, graph)) {
|
|
return GGML_STATUS_ALLOC_FAILED;
|
|
}
|
|
}
|
|
|
|
return ggml_backend_sched_compute_splits(sched);
|
|
}
|
|
|
|
void ggml_backend_sched_synchronize(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
for (int i = 0; i < sched->n_backends; i++) {
|
|
ggml_backend_synchronize(sched->backends[i]);
|
|
}
|
|
if (!sched->is_alloc) {
|
|
// if the graph is not already allocated, always use copy 0 after a synchronization
|
|
// this ensures that during generation the same copy is used every time,
|
|
// which avoids changes in the graph that could cause CUDA or other graphs to be disabled
|
|
sched->next_copy = 0;
|
|
}
|
|
}
|
|
|
|
void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data) {
|
|
GGML_ASSERT(sched);
|
|
sched->callback_eval = callback;
|
|
sched->callback_eval_user_data = user_data;
|
|
}
|
|
|
|
void ggml_backend_sched_set_copy_callback(ggml_backend_sched_t sched, ggml_backend_sched_copy_callback callback, void * user_data) {
|
|
GGML_ASSERT(sched);
|
|
sched->callback_copy = callback;
|
|
sched->callback_copy_user_data = user_data;
|
|
}
|
|
|
|
void ggml_backend_sched_set_realloc_callback(ggml_backend_sched_t sched, ggml_backend_sched_realloc_callback callback, void * user_data) {
|
|
GGML_ASSERT(sched);
|
|
sched->callback_realloc = callback;
|
|
sched->callback_realloc_user_data = user_data;
|
|
}
|
|
|
|
int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
return sched->n_splits;
|
|
}
|
|
|
|
int ggml_backend_sched_get_n_copies(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
return sched->n_copies;
|
|
}
|
|
|
|
int ggml_backend_sched_get_n_backends(ggml_backend_sched_t sched) {
|
|
GGML_ASSERT(sched);
|
|
return sched->n_backends;
|
|
}
|
|
|
|
ggml_backend_t ggml_backend_sched_get_backend(ggml_backend_sched_t sched, int i) {
|
|
GGML_ASSERT(sched);
|
|
GGML_ASSERT(i >= 0 && i < sched->n_backends);
|
|
return sched->backends[i];
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_sched_get_buffer_type(ggml_backend_sched_t sched, ggml_backend_t backend) {
|
|
GGML_ASSERT(sched);
|
|
int backend_index = ggml_backend_sched_backend_id(sched, backend);
|
|
GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
|
|
|
|
return sched->bufts[backend_index];
|
|
}
|
|
|
|
size_t ggml_backend_sched_get_buffer_size(ggml_backend_sched_t sched, ggml_backend_t backend) {
|
|
GGML_ASSERT(sched);
|
|
int backend_index = ggml_backend_sched_backend_id(sched, backend);
|
|
GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
|
|
|
|
return ggml_gallocr_get_buffer_size(sched->galloc, backend_index);
|
|
}
|
|
|
|
void ggml_backend_sched_set_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend) {
|
|
GGML_ASSERT(sched);
|
|
int backend_index = ggml_backend_sched_backend_id(sched, backend);
|
|
GGML_ASSERT(backend_index >= 0 && backend_index < sched->n_backends);
|
|
tensor_backend_id(node) = backend_index;
|
|
SET_CAUSE(node, "usr");
|
|
sched->is_reset = false;
|
|
}
|
|
|
|
ggml_backend_t ggml_backend_sched_get_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node) {
|
|
GGML_ASSERT(sched);
|
|
int backend_index = tensor_backend_id(node);
|
|
if (backend_index == -1) {
|
|
return NULL;
|
|
}
|
|
return sched->backends[backend_index];
|
|
}
|
|
|
|
// utils
|
|
|
|
bool ggml_op_alloc_size_may_expand(enum ggml_op op) {
|
|
switch (op) {
|
|
case GGML_OP_FLASH_ATTN_EXT:
|
|
case GGML_OP_MUL_MAT:
|
|
case GGML_OP_MUL_MAT_ID:
|
|
case GGML_OP_CUMSUM:
|
|
case GGML_OP_ARGSORT:
|
|
case GGML_OP_TOP_K:
|
|
case GGML_OP_ARGMAX:
|
|
case GGML_OP_CONV_2D:
|
|
return true;
|
|
default:
|
|
return false;
|
|
}
|
|
}
|
|
|
|
enum ggml_status ggml_backend_view_init(struct ggml_tensor * tensor) {
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->buffer == NULL);
|
|
GGML_ASSERT(tensor->view_src != NULL);
|
|
GGML_ASSERT(tensor->view_src->buffer != NULL);
|
|
GGML_ASSERT(tensor->view_src->data != NULL);
|
|
|
|
tensor->buffer = tensor->view_src->buffer;
|
|
tensor->data = (char *)tensor->view_src->data + tensor->view_offs;
|
|
return ggml_backend_buffer_init_tensor(tensor->buffer, tensor);
|
|
}
|
|
|
|
enum ggml_status ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr) {
|
|
GGML_ASSERT(tensor);
|
|
GGML_ASSERT(tensor->buffer == NULL);
|
|
GGML_ASSERT(tensor->data == NULL);
|
|
GGML_ASSERT(tensor->view_src == NULL);
|
|
GGML_ASSERT(addr >= ggml_backend_buffer_get_base(buffer));
|
|
GGML_ASSERT(ggml_backend_buffer_is_meta(buffer) ||
|
|
(char *) addr + ggml_backend_buffer_get_alloc_size(buffer, tensor) <=
|
|
(char *) ggml_backend_buffer_get_base(buffer) + ggml_backend_buffer_get_size(buffer));
|
|
|
|
tensor->buffer = buffer;
|
|
tensor->data = addr;
|
|
return ggml_backend_buffer_init_tensor(buffer, tensor);
|
|
}
|
|
|
|
static struct ggml_tensor * graph_copy_dup_tensor(struct ggml_hash_set hash_set, struct ggml_tensor ** node_copies,
|
|
struct ggml_context * ctx_allocated, struct ggml_context * ctx_unallocated, struct ggml_tensor * src) {
|
|
|
|
GGML_ASSERT(src != NULL);
|
|
GGML_ASSERT(src->data && "graph must be allocated");
|
|
|
|
size_t id = ggml_hash_insert(&hash_set, src);
|
|
if (id == GGML_HASHSET_ALREADY_EXISTS) {
|
|
return node_copies[ggml_hash_find(&hash_set, src)];
|
|
}
|
|
|
|
struct ggml_tensor * dst = ggml_dup_tensor_layout(src->data && !src->view_src ? ctx_allocated : ctx_unallocated, src);
|
|
if (src->view_src != NULL) {
|
|
dst->view_src = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, src->view_src);
|
|
dst->view_offs = src->view_offs;
|
|
}
|
|
dst->op = src->op;
|
|
dst->flags = src->flags;
|
|
memcpy(dst->op_params, src->op_params, sizeof(dst->op_params));
|
|
ggml_set_name(dst, src->name);
|
|
|
|
// copy src
|
|
for (int i = 0; i < GGML_MAX_SRC; i++) {
|
|
struct ggml_tensor * s = src->src[i];
|
|
if (s == NULL) {
|
|
continue;
|
|
}
|
|
dst->src[i] = graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, s);
|
|
}
|
|
|
|
node_copies[id] = dst;
|
|
return dst;
|
|
}
|
|
|
|
static void graph_copy_init_tensor(struct ggml_hash_set * hash_set, struct ggml_tensor ** node_copies, bool * node_init, struct ggml_tensor * src) {
|
|
size_t id = ggml_hash_find(hash_set, src);
|
|
if (node_init[id]) {
|
|
return;
|
|
}
|
|
node_init[id] = true;
|
|
|
|
struct ggml_tensor * dst = node_copies[id];
|
|
if (dst->view_src != NULL) {
|
|
graph_copy_init_tensor(hash_set, node_copies, node_init, src->view_src);
|
|
enum ggml_status status = ggml_backend_view_init(dst);
|
|
GGML_ASSERT(status == GGML_STATUS_SUCCESS);
|
|
}
|
|
else {
|
|
ggml_backend_tensor_copy(src, dst);
|
|
}
|
|
|
|
// init src
|
|
for (int i = 0; i < GGML_MAX_SRC; i++) {
|
|
struct ggml_tensor * s = src->src[i];
|
|
if (s == NULL) {
|
|
continue;
|
|
}
|
|
graph_copy_init_tensor(hash_set, node_copies, node_init, s);
|
|
}
|
|
}
|
|
|
|
struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph) {
|
|
GGML_ASSERT(graph);
|
|
struct ggml_hash_set hash_set = ggml_hash_set_new(graph->visited_hash_set.size);
|
|
struct ggml_tensor ** node_copies = (ggml_tensor **) calloc(hash_set.size, sizeof(node_copies[0])); // NOLINT
|
|
bool * node_init = (bool *) calloc(hash_set.size, sizeof(node_init[0]));
|
|
|
|
struct ggml_init_params params = {
|
|
/* .mem_size = */ ggml_tensor_overhead()*hash_set.size + ggml_graph_overhead_custom(graph->size, false),
|
|
/* .mem_buffer = */ NULL,
|
|
/* .no_alloc = */ true
|
|
};
|
|
|
|
struct ggml_context * ctx_allocated = ggml_init(params);
|
|
struct ggml_context * ctx_unallocated = ggml_init(params);
|
|
|
|
if (ctx_allocated == NULL || ctx_unallocated == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate context for graph copy\n", __func__);
|
|
ggml_hash_set_free(&hash_set);
|
|
free(node_copies);
|
|
free(node_init);
|
|
ggml_free(ctx_allocated);
|
|
ggml_free(ctx_unallocated);
|
|
return {
|
|
/* .buffer = */ NULL,
|
|
/* .ctx_allocated = */ NULL,
|
|
/* .ctx_unallocated = */ NULL,
|
|
/* .graph = */ NULL,
|
|
};
|
|
}
|
|
|
|
// dup nodes
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
graph_copy_dup_tensor(hash_set, node_copies, ctx_allocated, ctx_unallocated, node);
|
|
}
|
|
|
|
// allocate nodes
|
|
ggml_backend_buffer_t buffer = ggml_backend_alloc_ctx_tensors(ctx_allocated, backend);
|
|
if (buffer == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate buffer for graph copy\n", __func__);
|
|
ggml_hash_set_free(&hash_set);
|
|
free(node_copies);
|
|
free(node_init);
|
|
ggml_free(ctx_allocated);
|
|
ggml_free(ctx_unallocated);
|
|
return {
|
|
/* .buffer = */ NULL,
|
|
/* .ctx_allocated = */ NULL,
|
|
/* .ctx_unallocated = */ NULL,
|
|
/* .graph = */ NULL,
|
|
};
|
|
}
|
|
|
|
//printf("copy buffer size: %zu MB\n", ggml_backend_buffer_get_size(buffer) / 1024 / 1024);
|
|
|
|
// copy data and init views
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
graph_copy_init_tensor(&hash_set, node_copies, node_init, node);
|
|
}
|
|
|
|
// build graph copy
|
|
struct ggml_cgraph * graph_copy = ggml_new_graph_custom(ctx_allocated, graph->size, false);
|
|
for (int i = 0; i < graph->n_nodes; i++) {
|
|
struct ggml_tensor * node = graph->nodes[i];
|
|
struct ggml_tensor * node_copy = node_copies[ggml_hash_find(&hash_set, node)];
|
|
graph_copy->nodes[i] = node_copy;
|
|
}
|
|
graph_copy->n_nodes = graph->n_nodes;
|
|
|
|
ggml_hash_set_free(&hash_set);
|
|
free(node_copies);
|
|
free(node_init);
|
|
|
|
return {
|
|
/* .buffer = */ buffer,
|
|
/* .ctx_allocated = */ ctx_allocated,
|
|
/* .ctx_unallocated = */ ctx_unallocated,
|
|
/* .graph = */ graph_copy,
|
|
};
|
|
}
|
|
|
|
void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy) {
|
|
ggml_backend_buffer_free(copy.buffer);
|
|
ggml_free(copy.ctx_allocated);
|
|
ggml_free(copy.ctx_unallocated);
|
|
}
|
|
|
|
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) {
|
|
struct ggml_backend_graph_copy copy = ggml_backend_graph_copy(backend2, graph);
|
|
if (copy.buffer == NULL) {
|
|
return false;
|
|
}
|
|
|
|
struct ggml_cgraph * g1 = graph;
|
|
struct ggml_cgraph * g2 = copy.graph;
|
|
|
|
assert(g1->n_nodes == g2->n_nodes);
|
|
|
|
if (num_test_nodes != 0) {
|
|
GGML_ASSERT(test_nodes);
|
|
// Compute the whole graph and only test the output for specific tensors
|
|
ggml_backend_graph_compute(backend1, g1);
|
|
ggml_backend_graph_compute(backend2, g2);
|
|
|
|
bool verified = false;
|
|
for (int i = 0; i < g1->n_nodes; i++) {
|
|
for (size_t j = 0; j < num_test_nodes; ++j) {
|
|
if (g1->nodes[i] == test_nodes[j]) {
|
|
callback(i, g1->nodes[i], g2->nodes[i], user_data);
|
|
verified = true;
|
|
}
|
|
}
|
|
}
|
|
GGML_ASSERT(verified);
|
|
} else {
|
|
for (int i = 0; i < g1->n_nodes; i++) {
|
|
struct ggml_tensor * t1 = g1->nodes[i];
|
|
struct ggml_tensor * t2 = g2->nodes[i];
|
|
|
|
assert(t1->op == t2->op && ggml_are_same_layout(t1, t2));
|
|
|
|
struct ggml_cgraph g1v = ggml_graph_view(g1, i, i + 1);
|
|
struct ggml_cgraph g2v = ggml_graph_view(g2, i, i + 1);
|
|
|
|
ggml_backend_graph_compute(backend1, &g1v);
|
|
ggml_backend_graph_compute(backend2, &g2v);
|
|
|
|
if (ggml_is_view_op(t1->op)) {
|
|
continue;
|
|
}
|
|
|
|
// compare results, calculate rms etc
|
|
if (!callback(i, t1, t2, user_data)) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
ggml_backend_graph_copy_free(copy);
|
|
|
|
return true;
|
|
}
|
|
|
|
// CPU backend - buffer
|
|
|
|
static void * ggml_backend_cpu_buffer_get_base(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
uintptr_t data = (uintptr_t)buffer->context;
|
|
|
|
// align the buffer
|
|
if (data % TENSOR_ALIGNMENT != 0) {
|
|
data = GGML_PAD(data, TENSOR_ALIGNMENT);
|
|
}
|
|
|
|
return (void *)data;
|
|
}
|
|
|
|
static void ggml_backend_cpu_buffer_free_buffer(ggml_backend_buffer_t buffer) {
|
|
GGML_ASSERT(buffer);
|
|
ggml_aligned_free(buffer->context, buffer->size);
|
|
}
|
|
|
|
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) {
|
|
GGML_ASSERT(tensor);
|
|
memset((char *)tensor->data + offset, value, size);
|
|
|
|
GGML_UNUSED(buffer);
|
|
}
|
|
|
|
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) {
|
|
GGML_ASSERT(tensor);
|
|
memcpy((char *)tensor->data + offset, data, size);
|
|
|
|
GGML_UNUSED(buffer);
|
|
}
|
|
|
|
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) {
|
|
GGML_ASSERT(tensor);
|
|
memcpy(data, (const char *)tensor->data + offset, size);
|
|
|
|
GGML_UNUSED(buffer);
|
|
}
|
|
|
|
static bool ggml_backend_cpu_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const struct ggml_tensor * src, struct ggml_tensor * dst) {
|
|
GGML_ASSERT(src);
|
|
if (ggml_backend_buffer_is_host(src->buffer)) {
|
|
memcpy(dst->data, src->data, ggml_nbytes(src));
|
|
return true;
|
|
}
|
|
return false;
|
|
|
|
GGML_UNUSED(buffer);
|
|
}
|
|
|
|
static void ggml_backend_cpu_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
|
|
GGML_ASSERT(buffer);
|
|
memset(buffer->context, value, buffer->size);
|
|
}
|
|
|
|
static const struct ggml_backend_buffer_i ggml_backend_cpu_buffer_i = {
|
|
/* .free_buffer = */ ggml_backend_cpu_buffer_free_buffer,
|
|
/* .get_base = */ ggml_backend_cpu_buffer_get_base,
|
|
/* .init_tensor = */ NULL, // no initialization required
|
|
/* .memset_tensor = */ ggml_backend_cpu_buffer_memset_tensor,
|
|
/* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
|
|
/* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
|
|
/* .set_tensor_2d = */ NULL,
|
|
/* .get_tensor_2d = */ NULL,
|
|
/* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
|
|
/* .clear = */ ggml_backend_cpu_buffer_clear,
|
|
/* .reset = */ NULL,
|
|
/* .set_tensor_n = */ NULL,
|
|
/* .get_tensor_n = */ NULL,
|
|
/* .cpy_tensor_n = */ NULL,
|
|
};
|
|
|
|
static const struct ggml_backend_buffer_i ggml_backend_cpu_buffer_from_ptr_i = {
|
|
/* .free_buffer = */ NULL, // ptr is not owned by the buffer, so it does not need to be freed
|
|
/* .get_base = */ ggml_backend_cpu_buffer_get_base,
|
|
/* .init_tensor = */ NULL, // no initialization required
|
|
/* .memset_tensor = */ ggml_backend_cpu_buffer_memset_tensor,
|
|
/* .set_tensor = */ ggml_backend_cpu_buffer_set_tensor,
|
|
/* .get_tensor = */ ggml_backend_cpu_buffer_get_tensor,
|
|
/* .set_tensor_2d = */ NULL,
|
|
/* .get_tensor_2d = */ NULL,
|
|
/* .cpy_tensor = */ ggml_backend_cpu_buffer_cpy_tensor,
|
|
/* .clear = */ ggml_backend_cpu_buffer_clear,
|
|
/* .reset = */ NULL,
|
|
/* .set_tensor_n = */ NULL,
|
|
/* .get_tensor_n = */ NULL,
|
|
/* .cpy_tensor_n = */ NULL,
|
|
};
|
|
|
|
// CPU backend buffer type
|
|
|
|
// this buffer type is defined here to make it available to all backends
|
|
|
|
static const char * ggml_backend_cpu_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
|
|
return "CPU";
|
|
|
|
GGML_UNUSED(buft);
|
|
}
|
|
|
|
static ggml_backend_buffer_t ggml_backend_cpu_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
|
|
void * data = ggml_aligned_malloc(size);
|
|
|
|
if (data == NULL) {
|
|
GGML_LOG_ERROR("%s: failed to allocate buffer of size %zu\n", __func__, size);
|
|
return NULL;
|
|
}
|
|
|
|
return ggml_backend_buffer_init(buft, ggml_backend_cpu_buffer_i, data, size);
|
|
}
|
|
|
|
static size_t ggml_backend_cpu_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
|
|
return TENSOR_ALIGNMENT;
|
|
|
|
GGML_UNUSED(buft);
|
|
}
|
|
|
|
static bool ggml_backend_cpu_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
|
|
return true;
|
|
|
|
GGML_UNUSED(buft);
|
|
}
|
|
|
|
ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void) {
|
|
static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = {
|
|
/* .iface = */ {
|
|
/* .get_name = */ ggml_backend_cpu_buffer_type_get_name,
|
|
/* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer,
|
|
/* .alloc_buffer_n = */ NULL,
|
|
/* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
|
|
/* .get_max_size = */ NULL, // defaults to SIZE_MAX
|
|
/* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
|
|
/* .get_alloc_size_n = */ NULL,
|
|
/* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
|
|
},
|
|
/* .device = */ NULL, // FIXME ggml_backend_reg_dev_get(ggml_backend_cpu_reg(), 0),
|
|
/* .context = */ NULL,
|
|
};
|
|
|
|
return &ggml_backend_cpu_buffer_type;
|
|
}
|
|
|
|
static const char * ggml_backend_cpu_buffer_from_ptr_type_get_name(ggml_backend_buffer_type_t buft) {
|
|
return "CPU_Mapped";
|
|
|
|
GGML_UNUSED(buft);
|
|
}
|
|
|
|
static ggml_backend_buffer_type_t ggml_backend_cpu_buffer_from_ptr_type(void) {
|
|
static struct ggml_backend_buffer_type ggml_backend_cpu_buffer_type = {
|
|
/* .iface = */ {
|
|
/* .get_name = */ ggml_backend_cpu_buffer_from_ptr_type_get_name,
|
|
/* .alloc_buffer = */ ggml_backend_cpu_buffer_type_alloc_buffer,
|
|
/* .alloc_buffer_n = */ NULL,
|
|
/* .get_alignment = */ ggml_backend_cpu_buffer_type_get_alignment,
|
|
/* .get_max_size = */ NULL, // defaults to SIZE_MAX
|
|
/* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
|
|
/* .get_alloc_size_n = */ NULL,
|
|
/* .is_host = */ ggml_backend_cpu_buffer_type_is_host,
|
|
},
|
|
/* .device = */ NULL, // FIXME ggml_backend_reg_dev_get(ggml_backend_cpu_reg(), 0),
|
|
/* .context = */ NULL,
|
|
};
|
|
|
|
return &ggml_backend_cpu_buffer_type;
|
|
}
|
|
|
|
ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size) {
|
|
GGML_ASSERT((uintptr_t)ptr % TENSOR_ALIGNMENT == 0 && "buffer pointer must be aligned");
|
|
return ggml_backend_buffer_init(ggml_backend_cpu_buffer_from_ptr_type(), ggml_backend_cpu_buffer_from_ptr_i, ptr, size);
|
|
}
|