Commit c2e72d1 for stable-diffusion.cpp
commit c2e72d1cadaf96224e6155d2137b2b8a9ffb5965
Author: leejet <leejet714@gmail.com>
Date: Fri Dec 4 23:50:26 2026 +0800
fix: allow allocations after advisory memory prechecks (#2519)
diff --git a/docs/dgl.md b/docs/dgl.md
index 8573da1..5e4fd20 100644
--- a/docs/dgl.md
+++ b/docs/dgl.md
@@ -1864,14 +1864,16 @@ are released after use.
`max_ram` caps allocated host weight buffers across the context, including
pinned host buffers used by CUDA. Set it in GiB with `sd_dgl_ctx_set`.
-A value of `0` disables the explicit cap and keeps the system memory pressure
-check, which subtracts 1 GiB from the available RAM reported by the OS.
-On Windows, this also accounts for the remaining commit capacity, including
-CUDA weight staging, prefetch, and compute buffer allocations under WDDM. Device
-allocations reserve commit capacity without charging their size to physical RAM. Graph
-metadata allocations request space from the same memory manager and can reclaim
-idle weights before creating a scheduler. Temporary graph memory does not count
-against the host weight limit.
+A value of `0` disables the explicit cap. The memory manager uses the OS memory
+estimate with 1 GiB of headroom to choose weight placement, skip prefetch, and
+reclaim idle allocations. On Windows the estimate includes the current process's
+remaining commit and the pending commit for CUDA buffers under WDDM. If required
+weight or workspace buffers still exceed the estimate after reclamation, the
+manager warns and tries the allocation within any configured limit. Scheduler
+metadata still needs enough reported host memory because GGML can abort on
+allocation failure there. Graph measurement can fall back to smaller segments
+when segmentation is available. Temporary graph memory does not count against
+the host weight limit.
For CPU execution, automatic placement checks weight storage against this cap
and separately checks weights plus workspace against available system memory.
Lowering the cap trims idle weights immediately. Before a new allocation,
diff --git a/docs/guides/backend.md b/docs/guides/backend.md
index 1a0433e..5ea8b98 100644
--- a/docs/guides/backend.md
+++ b/docs/guides/backend.md
@@ -171,15 +171,20 @@ GiB", and with no budget set each device's free memory minus a 512 MiB margin
is used. These resolved GPU budgets, including the safety margin, also drive
the runner's graph-cut capacity checks.
-Runtime capacity checks also leave 512 MiB of currently free device memory for
-backend scratch buffers and pipelines, including with explicit backend assignments.
+Runtime capacity estimates reserve 512 MiB of free device memory for backend
+scratch buffers and pipelines, or 1 GiB on Windows with CUDA.
They cap free-memory reports by the device's total memory minus tracked
-resident allocations. Vulkan reports exceeding total memory are rejected on
-discrete GPUs because its heap-budget subtraction can underflow. On integrated
+resident allocations. A Vulkan report exceeding total memory yields a zero
+estimate on discrete GPUs because its heap-budget subtraction can underflow. On integrated
GPUs, a wrapped report triggers reclamation before the tracked estimate can be
accepted, subject to the byte checks and configured budgets. Other backends use
-the cap instead of treating such reports as zero free memory. Failed checks log
-the reported free and total memory alongside tracked weight and runtime allocations.
+the cap instead of treating such reports as zero free memory. These estimates
+can trigger segmentation, buffer reclamation, or a switch to synchronous loading.
+Multi-GPU layer splitting can plan using the devices' total capacities when
+their current free memory does not leave room for the layout. Required
+allocations within the configured VRAM limit are attempted if the
+estimate still falls short. The warning includes the estimated budget and the
+tracked weight and runtime allocations.
With `--mmap`, device-backed mappings count toward these budgets at their full
mapped-file size, once per device buffer even when multiple parameter blocks
share it. Mappings retained in the loader cache continue to count.
@@ -210,10 +215,9 @@ components to another GPU even when a split layout would fit; use
For example, a diffusion model whose full weights exceed the main GPU's budget
keeps the weights that fit on the GPU and stores the rest in RAM. Automatic graph
segmentation then loads the required weights for each segment.
-`--disable-segmented-compute` still disables segmentation. Compute reserves are
-estimates. Actual segment weights, compute buffers and caches must still fit the
-runner's capacity checks, so not every resolution or frame count is guaranteed to
-fit, and auto-fit does not change a component to CPU computation solely because
+`--disable-segmented-compute` still disables segmentation. Actual segment weights,
+compute buffers and caches must fit in device memory and within any configured
+VRAM limit. Auto-fit does not change a component to CPU computation solely because
its full weights exceed VRAM.
If a VAE decode fails, decoding retries with spatial tiling even when `--auto-fit`
is off; supported video decoders try temporal tiling first and can then add
diff --git a/src/core/backend_fit.cpp b/src/core/backend_fit.cpp
index 1401030..1134970 100644
--- a/src/core/backend_fit.cpp
+++ b/src/core/backend_fit.cpp
@@ -80,13 +80,18 @@ namespace sd::backend_fit {
return out;
}
- int64_t available_ram_bytes() {
+ int64_t HostMemory::available_bytes() const {
+ if (physical_bytes < 0)
+ return commit_bytes;
+ return commit_bytes < 0 ? physical_bytes : std::min(physical_bytes, commit_bytes);
+ }
+
+ HostMemory available_host_memory() {
#if defined(_WIN32)
MEMORYSTATUSEX status{};
status.dwLength = sizeof(status);
if (GlobalMemoryStatusEx(&status)) {
- // Commit exhaustion can reject allocations while physical RAM is still available.
- return (int64_t)std::min(status.ullAvailPhys, status.ullAvailPageFile);
+ return {static_cast<int64_t>(status.ullAvailPhys), static_cast<int64_t>(status.ullAvailPageFile)};
}
#elif defined(__linux__)
std::ifstream meminfo("/proc/meminfo");
@@ -94,7 +99,7 @@ namespace sd::backend_fit {
int64_t kib = 0;
while (meminfo >> key >> kib >> unit) {
if (key == "MemAvailable:" && unit == "kB" && kib >= 0) {
- return kib * 1024;
+ return {kib * 1024};
}
}
#elif defined(__APPLE__)
@@ -106,20 +111,10 @@ namespace sd::backend_fit {
host_statistics64(host, HOST_VM_INFO64, (host_info64_t)&stats, &count) == KERN_SUCCESS;
mach_port_deallocate(mach_task_self(), host);
if (ok) {
- return ((int64_t)stats.free_count + stats.inactive_count) * page_size;
+ return {static_cast<int64_t>((stats.free_count + uint64_t{stats.inactive_count}) * page_size)};
}
#endif
- return -1;
- }
-
- int64_t available_commit_bytes() {
-#ifdef _WIN32
- MEMORYSTATUSEX status{};
- status.dwLength = sizeof(status);
- if (GlobalMemoryStatusEx(&status))
- return static_cast<int64_t>(status.ullAvailPageFile);
-#endif
- return -1;
+ return {};
}
static size_t select_main_device(const std::vector<Device>& devices) {
diff --git a/src/core/backend_fit.h b/src/core/backend_fit.h
index 40d9b09..ec4a1df 100644
--- a/src/core/backend_fit.h
+++ b/src/core/backend_fit.h
@@ -1,6 +1,7 @@
#ifndef __SD_BACKEND_FIT_H__
#define __SD_BACKEND_FIT_H__
+#include <cstdint>
#include <functional>
#include <string>
#include <vector>
@@ -14,8 +15,13 @@ namespace sd {
namespace sd::backend_fit {
- int64_t available_ram_bytes();
- int64_t available_commit_bytes();
+ struct HostMemory {
+ int64_t physical_bytes = -1;
+ int64_t commit_bytes = -1;
+ int64_t available_bytes() const;
+ };
+
+ HostMemory available_host_memory();
using AvailableVRAM = std::function<size_t(ggml_backend_dev_t, size_t, size_t)>;
diff --git a/src/core/compute_workspace.cpp b/src/core/compute_workspace.cpp
index 4896a41..9b01c3d 100644
--- a/src/core/compute_workspace.cpp
+++ b/src/core/compute_workspace.cpp
@@ -26,12 +26,12 @@ namespace sd {
}
}
- ggml_backend_sched_t ComputeWorkspace::make_scheduler(size_t graph_size, const std::function<bool(size_t)>& ensure_host_memory) {
+ ggml_backend_sched_t ComputeWorkspace::make_scheduler(size_t graph_size, const CheckHostMemory& ensure_host_memory) {
// Round up ggml's 30 split inputs and two tensor copies per graph node.
const auto per_node = 64 * ggml_tensor_overhead();
const auto graph_bytes = ggml_graph_overhead_custom(graph_size, false);
if (graph_size > (std::numeric_limits<size_t>::max() - graph_bytes) / per_node ||
- (ensure_host_memory && !ensure_host_memory(graph_size * per_node + graph_bytes)))
+ (ensure_host_memory && !ensure_host_memory(graph_size * per_node + graph_bytes, true)))
return nullptr;
std::vector<ggml_backend_t> backends{backend_};
backends.insert(backends.end(), extra_backends_.begin(), extra_backends_.end());
@@ -76,7 +76,7 @@ namespace sd {
release_scheduler();
}
- bool ComputeWorkspace::allocate(ggml_cgraph* graph, const Measurement& measurement, const AssignNodes& assign_nodes, const std::function<bool(size_t)>& ensure_host_memory) {
+ bool ComputeWorkspace::allocate(ggml_cgraph* graph, const Measurement& measurement, const AssignNodes& assign_nodes, const CheckHostMemory& ensure_host_memory) {
GGML_ASSERT(!active_);
const size_t capacity = static_cast<size_t>(ggml_graph_n_nodes(graph) + ggml_graph_n_leafs(graph)) + 8;
if (scheduler_ == nullptr || capacity > scheduler_capacity_) {
@@ -94,7 +94,7 @@ namespace sd {
host_bytes += std::min(pending, SIZE_MAX - host_bytes);
}
}
- if (ensure_host_memory && !ensure_host_memory(host_bytes))
+ if (ensure_host_memory && !ensure_host_memory(host_bytes, false))
return false;
ggml_backend_sched_reset(scheduler_);
assign_nodes(scheduler_, graph);
@@ -116,7 +116,7 @@ namespace sd {
const std::function<ggml_backend_t(const ggml_tensor*)>& external_backend,
const AssignNodes& assign_nodes,
bool cache_measurement,
- const std::function<bool(size_t)>& ensure_host_memory) {
+ const CheckHostMemory& ensure_host_memory) {
std::vector<const ggml_tensor*> tensors;
std::unordered_set<const ggml_tensor*> seen;
auto visit = [&](const ggml_tensor* tensor) {
diff --git a/src/core/compute_workspace.h b/src/core/compute_workspace.h
index f6f14e0..c566b8c 100644
--- a/src/core/compute_workspace.h
+++ b/src/core/compute_workspace.h
@@ -8,6 +8,8 @@
#include "ggml-backend.h"
namespace sd {
+ using CheckHostMemory = std::function<bool(size_t bytes, bool require_available)>;
+
struct BackendBufferSize {
ggml_backend_t backend = nullptr;
size_t bytes = 0;
@@ -27,7 +29,7 @@ namespace sd {
};
std::array<CachedMeasurement, 2> measurement_cache_;
- ggml_backend_sched_t make_scheduler(size_t graph_size, const std::function<bool(size_t)>& ensure_host_memory);
+ ggml_backend_sched_t make_scheduler(size_t graph_size, const CheckHostMemory& ensure_host_memory);
bool release_scheduler();
public:
@@ -45,13 +47,13 @@ namespace sd {
void set_extra_backends(const std::vector<ggml_backend_t>& backends);
bool prepare(const Measurement& measurement);
bool release_excess(const Measurement& measurement);
- bool allocate(ggml_cgraph* graph, const Measurement& measurement, const AssignNodes& assign_nodes, const std::function<bool(size_t)>& ensure_host_memory = {});
+ bool allocate(ggml_cgraph* graph, const Measurement& measurement, const AssignNodes& assign_nodes, const CheckHostMemory& ensure_host_memory = {});
Measurement measure(
ggml_cgraph* graph,
const std::function<ggml_backend_t(const ggml_tensor*)>& external_backend,
const AssignNodes& assign_nodes,
- bool cache_measurement = false,
- const std::function<bool(size_t)>& ensure_host_memory = {});
+ bool cache_measurement = false,
+ const CheckHostMemory& ensure_host_memory = {});
void synchronize() const;
bool segment_end() noexcept;
bool release();
diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp
index e2e3f43..c04d4d2 100644
--- a/src/core/execution_engine.cpp
+++ b/src/core/execution_engine.cpp
@@ -411,8 +411,8 @@ namespace sd {
auto assign_nodes = [&](ggml_backend_sched_t scheduler, ggml_cgraph* copy) {
pin_multi_device_nodes(scheduler, copy, graph);
};
- return session_.workspace_.measure(graph, external_backend, assign_nodes, !is_multi_device(), [&](size_t bytes) {
- return manager_ == nullptr || manager_->ensure_host_memory(bytes, task_.weights);
+ return session_.workspace_.measure(graph, external_backend, assign_nodes, !is_multi_device(), [&](size_t bytes, bool require_available) {
+ return manager_ == nullptr || manager_->ensure_host_memory(bytes, task_.weights, 0, require_available);
});
}
@@ -563,10 +563,12 @@ namespace sd {
if (!segmented) {
full_measurement = measure(graph);
if (full_measurement.buffers.empty()) {
- last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
- return false;
- }
- if (can_segment) {
+ if (!can_segment) {
+ last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
+ return false;
+ }
+ segmented = true;
+ } else if (can_segment) {
// Planning headroom absorbs allocation estimate drift; execution keeps the normal limits.
constexpr size_t planning_headroom = 128ULL * 1024ULL * 1024ULL;
auto requests = memory_requests(full_measurement.buffers, session_.cache_.pending_bytes(graph));
@@ -722,17 +724,19 @@ namespace sd {
return fail_segment("output cache allocation");
}
new_cache_bytes = add_bytes(last ? 0 : session_.cut_cache_.estimate_output_bytes(graph, segment), session_.cache_.pending_bytes(segment_graph));
- auto ensure_host_memory = [&](size_t bytes) {
+ auto ensure_host_memory = [&](size_t bytes, bool require_available) {
size_t device_commit = 0;
#ifdef _WIN32
- for (const auto& size : measurement.buffers) {
- if (sd_backend_is(size.backend, "CUDA")) {
- const auto pending = size.bytes - std::min(size.bytes, session_.workspace_.bytes(size.backend));
- device_commit = add_bytes(device_commit, pending);
+ if (!require_available) {
+ for (const auto& size : measurement.buffers) {
+ if (sd_backend_is(size.backend, "CUDA")) {
+ const auto pending = size.bytes - std::min(size.bytes, session_.workspace_.bytes(size.backend));
+ device_commit = add_bytes(device_commit, pending);
+ }
}
}
#endif
- return manager == nullptr || manager->ensure_host_memory(bytes, weights.params(index), device_commit);
+ return manager == nullptr || manager->ensure_host_memory(bytes, weights.params(index), device_commit, require_available);
};
if (!session_.workspace_.allocate(
segment_graph, measurement, [&](ggml_backend_sched_t scheduler, ggml_cgraph* current) { pin_multi_device_nodes(scheduler, current); }, ensure_host_memory)) {
@@ -965,8 +969,7 @@ namespace sd {
if (available.fits(true)) {
return true;
}
- if (sd_backend_is(request.compute_backend, "Vulkan") &&
- available.required_budget_bytes <= available.available_budget_bytes) {
+ if (sd_backend_is(request.compute_backend, "Vulkan") && available.fits_budget()) {
ggml_backend_synchronize(request.compute_backend);
sd_backend_clear_buffer_cache(request.compute_backend);
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(100);
@@ -975,7 +978,7 @@ namespace sd {
if (available.fits(true)) {
return true;
}
- if (available.required_budget_bytes > available.available_budget_bytes) {
+ if (!available.fits_budget()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
@@ -984,18 +987,25 @@ namespace sd {
if (request.quiet) {
return false;
}
- available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect,
- !request.recoverable);
- 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));
- const auto budget_bytes = available.available_budget_bytes == SIZE_MAX
- ? std::string("unlimited")
- : sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0));
- auto message = sd_format("execution engine cannot make enough memory available on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
- ggml_backend_name(request.compute_backend),
- available.required_device_bytes / (1024.0 * 1024.0),
- available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
+ available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect,
+ !request.recoverable);
+ if (available.fits(true))
+ return true;
+ const bool budget_allows = available.fits_budget();
+ 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));
+ const auto budget_bytes = available.available_budget_bytes == SIZE_MAX
+ ? std::string("unlimited")
+ : sd_format("%.2f MB", available.available_budget_bytes / (1024.0 * 1024.0));
+ auto message = sd_format("device memory precheck on %s: need %.2f MB device / %.2f MB budget, available %s device / %s budget",
+ ggml_backend_name(request.compute_backend),
+ available.required_device_bytes / (1024.0 * 1024.0),
+ available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
+ if (budget_allows) {
+ LOG_WARN("%s. Continuing with the backend allocation", message.c_str());
+ return true;
+ }
if (request.recoverable)
LOG_INFO("%s", message.c_str());
else
diff --git a/src/core/layer_split_partition.cpp b/src/core/layer_split_partition.cpp
index 67b92ee..6429c66 100644
--- a/src/core/layer_split_partition.cpp
+++ b/src/core/layer_split_partition.cpp
@@ -73,33 +73,9 @@ namespace sd {
return backend_index == 0 ? primary_backend_vram_limit : 0;
}
- // Capacity of a device that reports no free memory and has no VRAM limit.
+ // Capacity of a device without a memory estimate or configured limit.
static constexpr int64_t graph_cut_layer_split_unknown_capacity = std::numeric_limits<int64_t>::max() / 4;
- static std::vector<int64_t> graph_cut_layer_split_backend_capacities(const std::vector<ggml_backend_t>& backends,
- const std::vector<size_t>& backend_vram_limits,
- size_t primary_backend_vram_limit) {
- std::vector<int64_t> capacities(backends.size(), graph_cut_layer_split_unknown_capacity);
- constexpr int64_t compute_headroom_bytes = 2ll * 1024 * 1024 * 1024;
- for (size_t i = 0; i < backends.size(); i++) {
- ggml_backend_dev_t dev = ggml_backend_get_device(backends[i]);
- size_t free_bytes = 0, total_bytes = 0;
- if (dev != nullptr) {
- ggml_backend_dev_memory(dev, &free_bytes, &total_bytes);
- }
- if (free_bytes > 0) {
- capacities[i] = std::max<int64_t>((int64_t)free_bytes - compute_headroom_bytes, 0);
- }
- size_t limit_bytes = graph_cut_layer_split_backend_vram_limit(backend_vram_limits,
- i,
- primary_backend_vram_limit);
- if (limit_bytes > 0) {
- capacities[i] = std::min<int64_t>(capacities[i], (int64_t)limit_bytes);
- }
- }
- return capacities;
- }
-
// Whether filling the devices in order, each up to `fraction` of its capacity, places every
// segment. Mirrors the placement loop in partition_graph_cut_layer_split().
static bool graph_cut_layer_split_fits(const std::vector<int64_t>& segment_bytes,
@@ -196,19 +172,47 @@ namespace sd {
return false;
}
- std::vector<int64_t> backend_capacities = graph_cut_layer_split_backend_capacities(split_backends,
- backend_vram_limits,
- primary_backend_vram_limit);
// Existing placements may already occupy the reported free VRAM. Reuse
// them; execution checks missing weights and reclaims memory as needed.
const bool reuse_assignments = std::all_of(seen_params.begin(), seen_params.end(), [&](ggml_tensor* param) {
return param_assignments.count(param) != 0;
});
- // Move to the next device at the proportional fill limit; the capacity stays the hard limit.
- const std::vector<int64_t> backend_limits = reuse_assignments
- ? backend_capacities
- : graph_cut_layer_split_fill_limits(segment_param_bytes, backend_capacities);
+ std::vector<int64_t> backend_limits;
+ if (!reuse_assignments) {
+ constexpr uint64_t compute_headroom = 2ULL * 1024 * 1024 * 1024;
+ constexpr uint64_t unknown = graph_cut_layer_split_unknown_capacity;
+ std::vector<int64_t> configured_limits;
+ std::vector<int64_t> total_capacities;
+ std::vector<int64_t> free_capacities;
+ for (size_t i = 0; i < split_backends.size(); ++i) {
+ const auto limit = graph_cut_layer_split_backend_vram_limit(backend_vram_limits, i, primary_backend_vram_limit);
+ const auto configured = limit == 0 ? unknown : std::min<uint64_t>(limit, unknown);
+ size_t free_bytes = 0, total_bytes = 0;
+ auto device = ggml_backend_get_device(split_backends[i]);
+ if (device != nullptr) {
+ ggml_backend_dev_memory(device, &free_bytes, &total_bytes);
+ }
+ configured_limits.push_back(configured);
+ const auto total = total_bytes == 0 ? configured : std::min<uint64_t>(total_bytes, configured);
+ total_capacities.push_back(total);
+ const auto free = free_bytes > 0 ? free_bytes - std::min<uint64_t>(free_bytes, compute_headroom) : total;
+ free_capacities.push_back(std::min(free, total));
+ }
+ if (!graph_cut_layer_split_fits(segment_param_bytes, configured_limits, 1.0)) {
+ LOG_ERROR("%s graph-cut layer split exceeds the configured VRAM limits", desc);
+ return false;
+ }
+ const auto* capacities = &free_capacities;
+ if (!graph_cut_layer_split_fits(segment_param_bytes, free_capacities, 1.0)) {
+ LOG_WARN("%s graph-cut layer split cannot place all segments using reported free VRAM. Trying placement with capacity reclamation",
+ desc);
+ capacities = graph_cut_layer_split_fits(segment_param_bytes, total_capacities, 1.0)
+ ? &total_capacities
+ : &configured_limits;
+ }
+ backend_limits = graph_cut_layer_split_fill_limits(segment_param_bytes, *capacities);
+ }
std::vector<ggml_backend_t> backend_by_segment(plan.segments.size(), split_backends[0]);
size_t current_backend = 0;
@@ -221,15 +225,6 @@ namespace sd {
current_backend++;
current_used = 0;
}
- if (!reuse_assignments && bytes > 0 && current_used + bytes > backend_capacities[current_backend]) {
- LOG_ERROR("%s graph-cut layer split: segment %zu needs %.1f MB on %s, but only %.1f MB is available under current VRAM limits",
- desc,
- seg_idx,
- (current_used + bytes) / (1024.0 * 1024.0),
- layer_split_backend_device_display_name(split_backends[current_backend]).c_str(),
- backend_capacities[current_backend] / (1024.0 * 1024.0));
- return false;
- }
current_used += bytes;
for (ggml_tensor* param : segment_params[seg_idx]) {
diff --git a/src/device_residency_manager.h b/src/device_residency_manager.h
index 0fe758e..d61c04d 100644
--- a/src/device_residency_manager.h
+++ b/src/device_residency_manager.h
@@ -125,11 +125,14 @@ struct DeviceMemoryCapacity {
requires_reclamation = overcommitted_bytes != 0;
}
+ bool fits_budget() const {
+ return valid && !requires_reclamation && required_budget_bytes <= available_budget_bytes;
+ }
+
bool fits(bool after_reclamation = false) const {
- return valid && !requires_reclamation &&
+ return fits_budget() &&
(after_reclamation || !wrapped_device_report) &&
- required_device_bytes <= available_device_bytes &&
- required_budget_bytes <= available_budget_bytes;
+ required_device_bytes <= available_device_bytes;
}
};
@@ -174,8 +177,8 @@ public:
virtual bool segmented_compute_enabled() const = 0;
virtual bool prefetch_enabled() const = 0;
virtual size_t context_vram_limit(ggml_backend_t) const { return 0; }
- // Device bytes consume Windows commit without consuming physical host RAM.
- virtual bool ensure_host_memory(size_t, const std::vector<ggml_tensor*>&, size_t = 0) { return true; }
+ // The scheduler may abort on host OOM. Buffer allocations can report failure.
+ virtual bool ensure_host_memory(size_t, const std::vector<ggml_tensor*>&, size_t = 0, bool = false) { return true; }
virtual void register_runtime_owner(uintptr_t owner_id) = 0;
virtual void remove_runtime_owner(uintptr_t owner_id) = 0;
// Capacity requests select their backend's weights; protection spans all backends.
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index e90b285..36664ee 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -870,7 +870,7 @@ bool ModelManager::cache_merged_lora_weights(const ComputeStagingBlock& block) {
size_t available = 0;
const bool spill = lora_batch_spills_ != nullptr;
// A completed batch needs its merged copy back. Outside the merge, caching is optional.
- if (bytes == SIZE_MAX || !(spill ? ensure_host_capacity(bytes, {}, true, 0, true)
+ if (bytes == SIZE_MAX || !(spill ? ensure_host_capacity(bytes, {}, true, 0, HostCapacityPolicy::Optional)
: fits_host_capacity(bytes, true, 0, available)))
return !spill;
host->buffer = copy_weights(host_buft, block.compute_backend, copies, bytes);
@@ -1096,9 +1096,12 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
ggml_backend_buffer_t compute_buffer =
ggml_backend_alloc_ctx_tensors_from_buft(staging_ctx, staging_buft);
if (compute_buffer == nullptr) {
- capacity_failure = !ggml_backend_buft_is_host(staging_buft);
- LOG_ERROR("model manager alloc compute params backend buffer failed, num_tensors = %zu",
- staged_tensors.size());
+ capacity_failure = !ggml_backend_buft_is_host(staging_buft);
+ const auto message = sd_format("model manager failed to allocate a %zu-byte weight staging buffer on %s",
+ bytes, ggml_backend_name(compute_backend));
+ if (!capacity_failure)
+ host_memory_error_ = message;
+ LOG_ERROR("%s", message.c_str());
ggml_free(staging_ctx);
return false;
}
@@ -1391,7 +1394,8 @@ bool ModelManager::fits_host_capacity(size_t pending, bool weight_allocation, si
constexpr size_t headroom = 1024ULL * 1024 * 1024;
const size_t resident = max_ram_bytes_ ? host_weight_bytes() : 0;
available = weight_allocation && max_ram_bytes_ ? max_ram_bytes_ - std::min(max_ram_bytes_, resident) : SIZE_MAX;
- const int64_t free_ram = sd::backend_fit::available_ram_bytes();
+ const auto memory = sd::backend_fit::available_host_memory();
+ const int64_t free_ram = memory.available_bytes();
if (free_ram >= 0) {
const auto free_bytes = static_cast<uint64_t>(free_ram);
available = static_cast<size_t>(std::min<uint64_t>(
@@ -1400,7 +1404,7 @@ bool ModelManager::fits_host_capacity(size_t pending, bool weight_allocation, si
return false;
}
if (pending_device_commit > 0) {
- const int64_t free_commit = sd::backend_fit::available_commit_bytes();
+ const int64_t free_commit = memory.commit_bytes;
if (free_commit >= 0) {
const auto free_bytes = static_cast<uint64_t>(free_commit);
const auto reserve = pending_device_commit + std::min(headroom, SIZE_MAX - pending_device_commit);
@@ -1414,9 +1418,10 @@ bool ModelManager::fits_host_capacity(size_t pending, bool weight_allocation, si
return pending <= available && (!max_ram_bytes_ || resident <= max_ram_bytes_);
}
-bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation, size_t pending_device_commit, bool optional, const sd::weights::PriorityLimit* limit) {
- size_t available = 0;
- auto fits = [&] { return fits_host_capacity(pending, weight_allocation, pending_device_commit, available); };
+bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation, size_t pending_device_commit, HostCapacityPolicy policy, const sd::weights::PriorityLimit* limit) {
+ size_t available = 0;
+ auto fits = [&] { return fits_host_capacity(pending, weight_allocation, pending_device_commit, available); };
+ const bool optional = policy == HostCapacityPolicy::Optional;
host_memory_error_.clear();
if (fits_host_capacity_after_prefetch_reclaim(pending, weight_allocation, pending_device_commit, available))
return true;
@@ -1433,15 +1438,40 @@ bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<Tensor
if (optional) {
return false;
}
- const size_t resident = host_weight_bytes();
- host_memory_error_ = std::string(weight_allocation ? "RAM weight capacity exceeded. Requested " : "RAM graph capacity exceeded. Requested ") + std::to_string(pending) +
- " bytes, " + std::to_string(available) + " bytes available, " +
- std::to_string(resident) + " bytes resident";
+ const size_t resident = host_weight_bytes();
+ const size_t pending_weights = weight_allocation ? pending : 0;
+ const bool fits_configured_limit = max_ram_bytes_ == 0 ||
+ (resident <= max_ram_bytes_ && pending_weights <= max_ram_bytes_ - resident);
+ if (fits_configured_limit) {
+ const auto memory = sd::backend_fit::available_host_memory();
+ const auto raw_free = memory.available_bytes();
+ // GGML's scheduler cannot report failure for all of its host allocations.
+ if (policy == HostCapacityPolicy::Advisory || raw_free < 0 || static_cast<uint64_t>(raw_free) >= pending) {
+ if (pending == 0 && pending_device_commit == 0)
+ return true;
+ LOG_WARN(
+ "host memory precheck estimated %zu bytes available for %zu host bytes and %zu pending device commit bytes "
+ "(latest available physical RAM %lld bytes, process commit %lld bytes). Trying allocation",
+ available, pending, pending_device_commit, static_cast<long long>(memory.physical_bytes),
+ static_cast<long long>(memory.commit_bytes));
+ return true;
+ }
+ available = static_cast<size_t>(raw_free);
+ }
+ const char* reason = policy == HostCapacityPolicy::Required && fits_configured_limit
+ ? "Insufficient reported host memory for scheduler metadata"
+ : "Configured host weight limit exceeded";
+ host_memory_error_ = std::string(reason) + ". Requested " + std::to_string(pending) +
+ " bytes, " + std::to_string(available) + " bytes available, " +
+ std::to_string(resident) + " bytes resident";
if (max_ram_bytes_)
host_memory_error_ += ", max_ram is " + std::to_string(max_ram_bytes_) + " bytes";
if (pending_device_commit)
host_memory_error_ += ", pending device commit is " + std::to_string(pending_device_commit) + " bytes";
- LOG_ERROR("%s", host_memory_error_.c_str());
+ if (fits_configured_limit)
+ LOG_WARN("%s", host_memory_error_.c_str());
+ else
+ LOG_ERROR("%s", host_memory_error_.c_str());
return false;
}
@@ -1454,9 +1484,10 @@ bool ModelManager::set_max_ram(size_t bytes) {
return false;
}
-bool ModelManager::ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit) {
+bool ModelManager::ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit, bool require_available) {
std::vector<TensorState*> states;
- return resolve_required_tensor_states(protected_params, states) && ensure_host_capacity(pending, states, false, pending_device_commit);
+ const auto policy = require_available ? HostCapacityPolicy::Required : HostCapacityPolicy::Advisory;
+ return resolve_required_tensor_states(protected_params, states) && ensure_host_capacity(pending, states, false, pending_device_commit, policy);
}
bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
@@ -1586,10 +1617,13 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
}
ggml_backend_buffer_t buffer = cached_buffer ? cached_buffer.release() : ggml_backend_buft_alloc_buffer(params_buft, chunk_size);
if (buffer == nullptr) {
- LOG_ERROR("model manager alloc params backend buffer failed, size = %.2fMB",
- chunk_size / (1024.0 * 1024.0));
- if (capacity_failure && !ggml_backend_buft_is_host(params_buft))
+ const auto message = sd_format("model manager failed to allocate a %zu-byte weight buffer from %s",
+ chunk_size, ggml_backend_buft_name(params_buft));
+ if (ggml_backend_buft_is_host(params_buft))
+ host_memory_error_ = message;
+ else if (capacity_failure)
*capacity_failure = true;
+ LOG_ERROR("%s", message.c_str());
return false;
}
ggml_backend_buffer_set_usage(buffer, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
@@ -1669,8 +1703,8 @@ sd::weights::ReadTarget ModelManager::read_target(const TensorState& state, ggml
}
bool ModelManager::load_tensors(const std::vector<TensorState*>& states,
- const std::vector<TensorState*>& need_alloc,
- uintptr_t prefetch_owner) {
+ const std::vector<TensorState*>& need_alloc,
+ uintptr_t prefetch_owner) {
// Collected after mmap and shared reuse, need_alloc contains the destinations safe to overwrite.
std::unordered_set<TensorState*> writable;
if (prefetch_owner)
@@ -1996,10 +2030,7 @@ ModelManager::RAMBudget ModelManager::available_ram_for_fit() const {
const size_t reclaimable = sd::weights::reclaimable_bytes(residency_snapshot(request, nullptr), request);
const auto resident = host_weight_bytes();
const auto fixed = resident - std::min(resident, reclaimable);
- int64_t free = sd::backend_fit::available_ram_bytes();
- const auto commit = sd::backend_fit::available_commit_bytes();
- if (commit >= 0)
- free = free < 0 ? commit : std::min(free, commit);
+ const int64_t free = sd::backend_fit::available_host_memory().available_bytes();
constexpr size_t reserve = 1024ULL * 1024 * 1024;
size_t available = free < 0 ? 0 : size_t(std::max<int64_t>(free - reserve, 0));
available += std::min(reclaimable, SIZE_MAX - available);
@@ -2234,9 +2265,11 @@ bool ModelManager::ensure_compute_backend_capacity(
if (backend == request.compute_backend)
continue;
const auto pending = request.pending_allocation_bytes;
- const DeviceMemoryRequest peer{backend, request.owner_id,
- pending > SIZE_MAX - missing ? SIZE_MAX : pending + missing,
- request.runtime_resident_bytes, limit};
+ DeviceMemoryRequest peer{backend, request.owner_id,
+ pending > SIZE_MAX - missing ? SIZE_MAX : pending + missing,
+ request.runtime_resident_bytes, limit};
+ peer.quiet = request.quiet;
+ peer.recoverable = request.recoverable;
if (!ensure_device_capacity(peer, {}, preferred_eviction_order, protected_weights, device_memory_error))
return false;
}
diff --git a/src/model_manager.h b/src/model_manager.h
index f6e1423..145668a 100644
--- a/src/model_manager.h
+++ b/src/model_manager.h
@@ -279,7 +279,10 @@ private:
sd::weights::Snapshot residency_snapshot(const sd::weights::Request& plan, ggml_backend_t backend) const;
bool fits_host_capacity(size_t pending, bool weight_allocation, size_t pending_device_commit, size_t& available) const;
bool fits_host_capacity_after_prefetch_reclaim(size_t pending, bool weight_allocation, size_t pending_device_commit, size_t& available);
- bool ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation = true, size_t pending_device_commit = 0, bool optional = false, const sd::weights::PriorityLimit* limit = nullptr);
+ enum class HostCapacityPolicy { Advisory,
+ Required,
+ Optional };
+ bool ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation = true, size_t pending_device_commit = 0, HostCapacityPolicy policy = HostCapacityPolicy::Advisory, const sd::weights::PriorityLimit* limit = nullptr);
bool alloc_params_buffers(const std::vector<TensorState*>& states,
const std::vector<TensorState*>& required_states,
std::vector<ParamsStorageBlock*>& created_storage_blocks,
@@ -441,7 +444,7 @@ public:
bool assign_compute_backend(const std::vector<ggml_tensor*>& tensors,
ggml_backend_t compute_backend) override;
bool prepare_params(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) override;
- bool ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit = 0) override;
+ bool ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit = 0, bool require_available = false) override;
void register_runtime_owner(uintptr_t owner_id) override;
void remove_runtime_owner(uintptr_t owner_id) override;
bool fits_compute_backend_capacity(const DeviceMemoryRequest& request,
@@ -587,8 +590,8 @@ public:
void update_runtime_residency(uintptr_t owner, ggml_backend_t backend, size_t bytes) override {
manager_->update_runtime_residency(owner, backend, bytes);
}
- bool ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit = 0) override {
- return manager_->ensure_host_memory(pending, protected_params, pending_device_commit);
+ bool ensure_host_memory(size_t pending, const std::vector<ggml_tensor*>& protected_params, size_t pending_device_commit = 0, bool require_available = false) override {
+ return manager_->ensure_host_memory(pending, protected_params, pending_device_commit, require_available);
}
bool ensure_compute_backend_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required,
diff --git a/src/model_manager_prefetch.cpp b/src/model_manager_prefetch.cpp
index 2d9ec52..b85ae19 100644
--- a/src/model_manager_prefetch.cpp
+++ b/src/model_manager_prefetch.cpp
@@ -122,7 +122,8 @@ bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer*
return false;
}
if (host_capacity &&
- !ensure_host_capacity(host_buffer ? bytes : 0, block.states, host_buffer, host_buffer || reuse_buffer ? 0 : bytes)) {
+ !ensure_host_capacity(host_buffer ? bytes : 0, block.states, host_buffer, host_buffer || reuse_buffer ? 0 : bytes,
+ HostCapacityPolicy::Optional)) {
return false;
}
}
@@ -572,8 +573,7 @@ const ggml_tensor* ModelManager::prefetched_file_tensor(uintptr_t owner, TensorS
return source == tensors.end() ? nullptr : source->second;
}
-bool ModelManager::fits_host_capacity_after_prefetch_reclaim(size_t pending, bool weight_allocation,
- size_t pending_device_commit, size_t& available) {
+bool ModelManager::fits_host_capacity_after_prefetch_reclaim(size_t pending, bool weight_allocation, size_t pending_device_commit, size_t& available) {
if (fits_host_capacity(pending, weight_allocation, pending_device_commit, available))
return true;
diff --git a/src/model_manager_reclaim.cpp b/src/model_manager_reclaim.cpp
index bdf714e..6ee843f 100644
--- a/src/model_manager_reclaim.cpp
+++ b/src/model_manager_reclaim.cpp
@@ -261,7 +261,7 @@ bool ModelManager::copy_params_storage_block(ParamsStorageBlock& block,
bool fits = false;
if (host) {
const sd::weights::PriorityLimit limit{next_use, last_use};
- fits = ensure_host_capacity(bytes, protected_list, true, 0, true, &limit);
+ fits = ensure_host_capacity(bytes, protected_list, true, 0, HostCapacityPolicy::Optional, &limit);
} else {
std::vector<ggml_tensor*> protected_params;
protected_params.reserve(protected_list.size());