Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/guides/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,13 @@ sd-cli -m model.safetensors -p "a cat" --backend diffusion=cuda0,vae=vulkan0 --m
```


The value is a shared per-device budget for managed weights and registered
runner compute/cache buffers. Live free memory can lower the effective limit
for each graph run. Driver contexts and allocations made outside the managed
model runners are not part of this accounting, so it is not a hard physical
VRAM cap.
The value is a shared per-device budget for managed weights, registered runner
compute and cache buffers, and idle buffers retained for reuse by ggml. The
runner trims the idle pool to make room for allocations. If a prefetch already
requires weight eviction, it can reuse a matching weight buffer directly.
Live free memory and a safety reserve also constrain allocations. Device-wide
VRAM usage can include driver contexts, unregistered backend scratch allocations,
and other processes.

Module names are case-insensitive. Hyphens and underscores in module names are ignored, so `clip_vision`, `clip-vision`, and `clipvision` are equivalent.

Expand Down
16 changes: 9 additions & 7 deletions docs/guides/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ See [backend selection](./backend.md) for full syntax.

`--offload-to-cpu` keeps the source parameters in system RAM and creates compute-side GPU replicas on demand. Unpinned replicas remain resident for reuse, but automatic graph-cut execution evicts them from the last segment backward when the next weight or compute allocation needs space. Disk-backed parameters follow the same policy without retaining a RAM source copy.

When a graph has cut markers and its missing weights plus incremental compute workspace exceed the available device headroom, it runs its fixed segment list in order. A reusable monolithic compute buffer is not counted as a new allocation. An explicit `--max-vram` budget deducts already-resident managed weights and compute/cache buffers registered by every runner sharing the device, so later graph runs remain segmented when the full graph exceeds the budget. The current segment's weights are pinned during compute, and the next parameter-bearing segment is prefetched when the device supports asynchronous transfer. No opt-in streaming flag is required.
When a graph has cut markers and its missing weights plus incremental compute workspace exceed the available device headroom, it runs its fixed segment list in order. An existing monolithic workspace can be reused without a new allocation. An explicit `--max-vram` budget includes resident managed weights, compute and cache buffers registered by runners sharing the device, and ggml's idle buffer pool. The current segment's weights are pinned during compute, and the next parameter-bearing segment is prefetched when the device supports asynchronous transfer. No opt-in streaming flag is required.

When choosing between monolithic and segmented execution, the runner requires
an additional 128 MiB of headroom in both available device memory and any explicit
Expand All @@ -170,12 +170,14 @@ allocator/scheduler capacity. Compatible gallocr reservations are reused across
graphs; idle workspaces can be reclaimed under pressure and are freed at runner
completion. Cross-graph caches survive individual graphs, but cut buffers do not.

On discrete Vulkan devices, runners reuse released device buffers of the same
size to reduce allocation overhead during segmented execution. This idle buffer
cache is limited to 1 GiB per device and is reclaimed before allocating a new
size or at runner completion. It is outside the managed `--max-vram` budget,
so physical VRAM usage can be higher. Set `GGML_VK_REUSE_BUFFERS=0` to disable
it. Unified-memory and host-memory modes do not use this cache.
CUDA, HIP, and discrete Vulkan can reuse released device buffers of the same
size. The pool retains up to 4 GiB per device for CUDA and HIP and up to 1 GiB
for Vulkan, subject to the remaining device budget. Under pressure, the runner
trims idle buffers and can pass a matching evicted CUDA or HIP weight buffer
directly to a prefetch. Set
`GGML_CUDA_REUSE_BUFFERS=0` for CUDA or HIP, or `GGML_VK_REUSE_BUFFERS=0` for
Vulkan, to disable the pool. Vulkan also disables the pool when it prefers host
memory. Unified-memory mode disables the pool.

Discrete NVIDIA and non-GCN AMD Vulkan devices use a separate transfer queue by
default when available and graphics queue use is disabled, so weight prefetch can overlap compute. Set
Expand Down
2 changes: 1 addition & 1 deletion examples/common/common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ ArgOptions SDContextParams::get_options() {
&rpc_servers},
{"",
"--max-vram",
"optional per-device budget in GiB for managed weights and runner buffers during automatic graph-cut execution. Accepts a single value or assignments by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without an explicit budget; a negative value reserves that much free VRAM",
"optional per-device budget in GiB for managed weights, runner buffers, and idle backend buffers. Accepts a single value or assignments by backend/device, e.g. 6 or cuda0=6,vulkan0=4. 0 uses live free VRAM without an explicit budget; a negative value reserves that much free VRAM",
0,
&max_vram},
};
Expand Down
33 changes: 21 additions & 12 deletions src/core/execution_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ namespace sd {
bool assign_graph_cut_layer_split_backends(ggml_cgraph* graph);
ComputeWorkspace::Measurement measure(ggml_cgraph* graph, const std::unordered_set<const ggml_tensor*>* external_outputs = nullptr);
std::vector<DeviceMemoryRequest> memory_requests(const std::vector<BackendBufferSize>& sizes, size_t pending_cache_bytes) const;
bool fits(const std::vector<DeviceMemoryRequest>& requests, const std::vector<ggml_tensor*>& params, bool allow_reclamation = false) const;
bool fits(const std::vector<DeviceMemoryRequest>& requests, const std::vector<ggml_tensor*>& params, DeviceMemoryCheck check) const;
bool execute_segment(ggml_cgraph* graph, int n_threads, const std::function<void()>& on_before_compute);
bool execute_graph(ggml_cgraph* graph, int n_threads, bool no_return, const std::function<bool()>& read_outputs);
bool is_multi_device() const { return !session_.extra_backends_.empty(); }
Expand Down Expand Up @@ -440,13 +440,13 @@ namespace sd {

bool GraphExecution::fits(const std::vector<DeviceMemoryRequest>& requests,
const std::vector<ggml_tensor*>& params,
bool allow_reclamation) const {
DeviceMemoryCheck check) const {
auto manager = manager_;
if (manager == nullptr) {
return params.empty();
}
for (const auto& request : requests) {
if (!manager->fits_compute_backend_capacity(request, params, allow_reclamation)) {
if (!manager->fits_compute_backend_capacity(request, params, check)) {
return false;
}
}
Expand Down Expand Up @@ -542,7 +542,7 @@ namespace sd {
session_.segmented_compute_ &&
cached_plan.valid && cached_plan.has_cuts && cached_plan.segments.size() > 1;
// An empty workspace request is a lower bound on the full graph's memory demand.
bool segmented = can_segment && !fits(memory_requests({{session_.backend_, 0}}, 0), params, true);
bool segmented = can_segment && !fits(memory_requests({{session_.backend_, 0}}, 0), params, DeviceMemoryCheck::Reclaimable);
ComputeWorkspace::Measurement full_measurement;
if (!segmented) {
full_measurement = measure(graph);
Expand All @@ -557,7 +557,7 @@ namespace sd {
for (auto& request : requests) {
request.pending_allocation_bytes = add_bytes(request.pending_allocation_bytes, planning_headroom);
}
segmented = !fits(requests, params, true);
segmented = !fits(requests, params, DeviceMemoryCheck::Reclaimable);
}
}
ggml_graph_cut::Plan monolithic_plan;
Expand Down Expand Up @@ -611,7 +611,7 @@ namespace sd {
}
return false;
};
session_.cut_cache_.prune(segment.live_cut_names);
auto unused_cut_outputs = session_.cut_cache_.prune(segment.live_cut_names);
bindings.reset(segment);
if (!bindings.bind_cached_inputs(segment, task_.description.c_str())) {
return fail_segment("input binding");
Expand Down Expand Up @@ -646,6 +646,9 @@ namespace sd {
}
}
}
// Transfer storage from consumed cuts before releasing it to the bounded pool.
session_.cut_cache_.bind_outputs(cache_outputs, &unused_cut_outputs);
unused_cut_outputs.clear();
auto measurement = segmented ? measure(segment_graph, &cache_outputs) : full_measurement;
if (!session_.workspace_.prepare(measurement)) {
last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
Expand All @@ -656,7 +659,7 @@ namespace sd {
auto ensure_capacity = [&]() {
sync_runtime_residency();
auto requests = memory_requests(measurement.buffers, new_cache_bytes);
if (fits(requests, weights.params(index))) {
if (fits(requests, weights.params(index), DeviceMemoryCheck::TrimBufferCache)) {
return true;
}
if (session_.workspace_.release_excess(measurement)) {
Expand Down Expand Up @@ -745,8 +748,10 @@ namespace sd {
last_compute_status_ = GGML_STATUS_FAILED;
return fail_segment("workspace synchronization");
}
// Final outputs and their callbacks may still be views of consumed cuts.
session_.cut_cache_.prune(segment.future_cut_names);
// Final outputs and callbacks can still refer to cuts until this point.
if (last) {
session_.cut_cache_.prune(segment.future_cut_names);
}
}
if (segments_changed || peak_compute_bytes != session_.logged_compute_bytes_) {
for (const auto& entry : peak_compute_bytes) {
Expand Down Expand Up @@ -888,7 +893,11 @@ namespace sd {
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error) {
GGML_ASSERT(&manager == manager_);
auto capacity = [&]() { return manager.inspect_compute_backend_capacity(request, required_params); };
auto* prefetch_buffer = request.prefetch_buffer;
if (prefetch_buffer != nullptr && !prefetch_buffer->buffer) {
prefetch_buffer->buffer.reset(sd_backend_try_alloc_buffer_from_cache(prefetch_buffer->type, prefetch_buffer->bytes));
}
auto capacity = [&]() { return manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::TrimBufferCache); };
const auto initial = capacity();
if (!initial.valid) {
return false;
Expand Down Expand Up @@ -947,7 +956,7 @@ namespace sd {
return lhs.last_use_epoch < rhs.last_use_epoch;
});
for (const auto& block : candidates) {
if (manager.evict_compute_backend_block(block) && capacity().fits(true)) {
if (manager.evict_compute_backend_block(block, prefetch_buffer) && capacity().fits(true)) {
return true;
}
}
Expand All @@ -971,7 +980,7 @@ namespace sd {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while (std::chrono::steady_clock::now() < deadline);
}
available = manager.inspect_compute_backend_capacity(request, required_params, true);
available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect, true);
const auto device_bytes = available.available_device_bytes == SIZE_MAX
? std::string("unknown")
: sd_format("%.2f MB", available.available_device_bytes / (1024.0 * 1024.0));
Expand Down
33 changes: 33 additions & 0 deletions src/core/ggml_extend_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,39 @@ void sd_backend_clear_buffer_cache(ggml_backend_t backend) {
}
}

bool sd_backend_get_buffer_cache_memory(ggml_backend_dev_t device, size_t& free_bytes, size_t& total_bytes, size_t& cached_bytes) {
auto reg = ggml_backend_dev_backend_reg(device);
using GetBufferCacheMemory = void (*)(ggml_backend_dev_t, size_t*, size_t*, size_t*);
auto fn = reinterpret_cast<GetBufferCacheMemory>(ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_buffer_cache_memory"));
if (fn == nullptr) {
ggml_backend_dev_memory(device, &free_bytes, &total_bytes);
cached_bytes = 0;
return false;
}
fn(device, &free_bytes, &total_bytes, &cached_bytes);
return true;
}

void sd_backend_set_buffer_cache_limit(ggml_backend_dev_t device, size_t bytes) {
auto reg = ggml_backend_dev_backend_reg(device);
using SetBufferCacheLimit = void (*)(ggml_backend_dev_t, size_t);
auto fn = reinterpret_cast<SetBufferCacheLimit>(ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_buffer_cache_limit"));
if (fn != nullptr) {
fn(device, bytes);
}
}

ggml_backend_buffer_t sd_backend_try_alloc_buffer_from_cache(ggml_backend_buffer_type_t buft, size_t bytes) {
auto device = ggml_backend_buft_get_device(buft);
if (device == nullptr) {
return nullptr;
}
auto reg = ggml_backend_dev_backend_reg(device);
using TryAllocBufferFromCache = ggml_backend_buffer_t (*)(ggml_backend_buffer_type_t, size_t);
auto fn = reinterpret_cast<TryAllocBufferFromCache>(ggml_backend_reg_get_proc_address(reg, "ggml_backend_try_alloc_buffer_from_cache"));
return fn != nullptr ? fn(buft, bytes) : nullptr;
}

const char* sd_get_system_info() {
static std::string cache_info = []() -> std::string {
ggml_backend_load_all_once();
Expand Down
3 changes: 3 additions & 0 deletions src/core/ggml_extend_backend.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ ggml_backend_t sd_backend_cpu_init();
bool sd_backend_cpu_set_n_threads(ggml_backend_t backend_cpu, int n_threads);
void sd_backend_set_buffer_cache_enabled(ggml_backend_t backend, bool enabled);
void sd_backend_clear_buffer_cache(ggml_backend_t backend);
bool sd_backend_get_buffer_cache_memory(ggml_backend_dev_t device, size_t& free_bytes, size_t& total_bytes, size_t& cached_bytes);
void sd_backend_set_buffer_cache_limit(ggml_backend_dev_t device, size_t bytes);
ggml_backend_buffer_t sd_backend_try_alloc_buffer_from_cache(ggml_backend_buffer_type_t buft, size_t bytes);

std::string sd_backend_resolve_name(const std::string& name);
bool sd_parse_backend_assignment(const std::string& spec, SDBackendAssignment* assignment, std::string* error);
Expand Down
59 changes: 52 additions & 7 deletions src/core/runner_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
#include <iterator>
#include <unordered_set>

#include "core/ggml_extend_backend.h"
#include "core/ggml_graph_cut.h"
#include "core/util.h"
#include "ggml-alloc.h"

namespace sd {
static std::unordered_set<const ggml_tensor*> cache_graph_tensors(ggml_cgraph* graph) {
Expand All @@ -24,7 +26,7 @@ namespace sd {
ggml_free(context);
}

std::unique_ptr<CachedTensor> CachedTensor::allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source) {
std::unique_ptr<CachedTensor> CachedTensor::allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source, bool reuse_only) {
auto entry = std::make_unique<CachedTensor>();
entry->context = ggml_init({2 * ggml_tensor_overhead(), nullptr, true});
if (entry->context == nullptr) {
Expand All @@ -34,7 +36,23 @@ namespace sd {
// Cut views are rebound with their original strides and offsets.
std::copy(std::begin(source->nb), std::end(source->nb), std::begin(entry->tensor->nb));
ggml_set_name(entry->tensor, name.c_str());
entry->buffer = ggml_backend_alloc_ctx_tensors(entry->context, backend);
if (reuse_only) {
auto buft = ggml_backend_get_default_buffer_type(backend);
if (buft == nullptr) {
return nullptr;
}
const auto bytes = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, entry->tensor), ggml_backend_buft_get_alignment(buft));
entry->buffer = sd_backend_try_alloc_buffer_from_cache(buft, bytes);
if (entry->buffer == nullptr) {
return nullptr;
}
auto allocator = ggml_tallocr_new(entry->buffer);
if (ggml_tallocr_alloc(&allocator, entry->tensor) != GGML_STATUS_SUCCESS) {
return nullptr;
}
} else {
entry->buffer = ggml_backend_alloc_ctx_tensors(entry->context, backend);
}
if (entry->buffer == nullptr) {
return nullptr;
}
Expand Down Expand Up @@ -168,11 +186,33 @@ namespace sd {
ggml_is_contiguous(tensor) && ggml_backend_supports_op(backend, tensor);
}

bool GraphCutTensorCache::bind_outputs(const std::unordered_set<const ggml_tensor*>& outputs) {
bool GraphCutTensorCache::bind_outputs(const std::unordered_set<const ggml_tensor*>& outputs, CachedTensors* unused_outputs) {
for (const ggml_tensor* output : outputs) {
auto tensor = const_cast<ggml_tensor*>(output);
auto entry = CachedTensor::allocate(backend_, tensor->name, tensor);
auto tensor = const_cast<ggml_tensor*>(output);
const auto cached = get(tensor->name);
if (cached != nullptr && tensor->buffer == cached->buffer && tensor->data == cached->data) {
continue;
}
std::unique_ptr<CachedTensor> entry;
if (unused_outputs != nullptr) {
auto match = std::find_if(unused_outputs->begin(), unused_outputs->end(), [&](const auto& item) {
const auto* previous = item.second->tensor;
return tensor->type == previous->type && ggml_are_same_shape(tensor, previous) &&
std::equal(std::begin(tensor->nb), std::end(tensor->nb), std::begin(previous->nb));
});
if (match != unused_outputs->end()) {
entry = std::move(match->second);
unused_outputs->erase(match);
ggml_set_name(entry->tensor, tensor->name);
}
}
if (entry == nullptr) {
entry = CachedTensor::allocate(backend_, tensor->name, tensor, unused_outputs != nullptr);
}
if (entry == nullptr) {
if (unused_outputs != nullptr) {
continue;
}
return false;
}
tensor->buffer = entry->tensor->buffer;
Expand Down Expand Up @@ -211,10 +251,15 @@ namespace sd {
return total_size;
}

void GraphCutTensorCache::prune(const std::unordered_set<std::string>& keep_names) {
CachedTensors GraphCutTensorCache::prune(const std::unordered_set<std::string>& keep_names) {
CachedTensors unused_outputs;
for (auto it = tensors_.begin(); it != tensors_.end();) {
it = keep_names.count(it->first) ? std::next(it) : tensors_.erase(it);
auto current = it++;
if (!keep_names.count(current->first)) {
unused_outputs.insert(tensors_.extract(current));
}
}
return unused_outputs;
}

ggml_status GraphCutTensorCache::capture(ggml_cgraph* graph,
Expand Down
Loading
Loading