Commit 5544c54 for stable-diffusion.cpp
commit 5544c543ec666e061c31c49b03f911496ba8e154
Author: leejet <leejet714@gmail.com>
Date: Wed Dec 2 00:56:30 2026 +0800
perf: optimize vulkan prefetch (#2479)
diff --git a/docs/guides/performance.md b/docs/guides/performance.md
index edbd6e2..cad93fe 100644
--- a/docs/guides/performance.md
+++ b/docs/guides/performance.md
@@ -148,7 +148,12 @@ 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.
-On Vulkan, CPU-offloaded weights use pageable system RAM, leaving the driver's host buffer capacity available for transfers.
+On AMD Vulkan devices, CPU-offloaded weights use pageable system RAM. Other
+Vulkan devices try to store offloaded weight blocks in `Vulkan_Host` and fall
+back to pageable RAM if pinned memory is unavailable. Prefetch submits a batch
+directly before compute when all its sources can upload without host staging.
+For batches with pageable weights, it submits after compute is queued and uses
+two reusable host staging slots of up to 64 MiB each per device when available.
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.
diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp
index 4b25a7f..e2e3f43 100644
--- a/src/core/execution_engine.cpp
+++ b/src/core/execution_engine.cpp
@@ -50,7 +50,7 @@ namespace sd {
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, DeviceMemoryCheck check) const;
- bool execute_segment(ggml_cgraph* graph, int n_threads, const std::function<void()>& on_before_compute);
+ bool execute_segment(ggml_cgraph* graph, int n_threads, SegmentWeightPipeline& weights);
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(); }
size_t retained_runtime_buffer_bytes(ggml_backend_t backend) const { return session_.resident_bytes(backend); }
@@ -460,7 +460,7 @@ namespace sd {
return true;
}
- bool GraphExecution::execute_segment(ggml_cgraph* graph, int n_threads, const std::function<void()>& on_before_compute) {
+ bool GraphExecution::execute_segment(ggml_cgraph* graph, int n_threads, SegmentWeightPipeline& weights) {
if (sd_backend_is_cpu(session_.backend_)) {
sd_backend_cpu_set_n_threads(session_.backend_, n_threads);
}
@@ -470,27 +470,36 @@ namespace sd {
auto scheduler = session_.workspace_.scheduler();
GGML_ASSERT(scheduler != nullptr);
ggml_backend_sched_set_eval_callback(scheduler, sd_get_backend_eval_callback(), sd_get_backend_eval_callback_data());
+ // Vulkan's pageable uploads fill host staging buffers on this thread.
+ const bool defer_prefetch = weights.submit_after_compute();
#ifndef SD_USE_UPSTREAM_GGML
struct BeforeComputeCallback {
ggml_backend_t backend;
- const std::function<void()>& callback;
+ SegmentWeightPipeline& weights;
bool invoked = false;
- } before_compute{session_.backend_, on_before_compute};
- ggml_backend_sched_set_compute_callback(
- scheduler, [](ggml_backend_t backend, void* data) {
- auto& hook = *static_cast<BeforeComputeCallback*>(data);
- if (backend == hook.backend && !hook.invoked) {
- hook.invoked = true;
- hook.callback();
- }
- },
- &before_compute);
- const auto status = ggml_backend_sched_graph_compute_async(scheduler, graph);
- ggml_backend_sched_set_compute_callback(scheduler, nullptr, nullptr);
+ } before_compute{session_.backend_, weights};
+ if (!defer_prefetch) {
+ ggml_backend_sched_set_compute_callback(
+ scheduler, [](ggml_backend_t backend, void* data) {
+ auto& hook = *static_cast<BeforeComputeCallback*>(data);
+ if (backend == hook.backend && !hook.invoked) {
+ hook.invoked = true;
+ hook.weights.submit_next();
+ }
+ },
+ &before_compute);
+ }
#else
- on_before_compute();
+ if (!defer_prefetch)
+ weights.submit_next();
+#endif
const auto status = ggml_backend_sched_graph_compute_async(scheduler, graph);
+#ifndef SD_USE_UPSTREAM_GGML
+ if (!defer_prefetch)
+ ggml_backend_sched_set_compute_callback(scheduler, nullptr, nullptr);
#endif
+ if (defer_prefetch && status == GGML_STATUS_SUCCESS)
+ weights.submit_next();
session_.workspace_.synchronize();
if (status != GGML_STATUS_SUCCESS) {
last_compute_status_ = status;
@@ -746,7 +755,7 @@ namespace sd {
}
LOG_DEBUG("%s executing segment %zu/%zu: %s", task_.description.c_str(),
index + 1, plan.segments.size(), segment.group_name.c_str());
- if (!execute_segment(segment_graph, n_threads, [&]() { weights.submit_next(); })) {
+ if (!execute_segment(segment_graph, n_threads, weights)) {
return fail_segment("execution");
}
auto cache_status = session_.cache_.capture(segment_graph);
diff --git a/src/core/ggml_extend_backend.cpp b/src/core/ggml_extend_backend.cpp
index de204bd..3569556 100644
--- a/src/core/ggml_extend_backend.cpp
+++ b/src/core/ggml_extend_backend.cpp
@@ -358,6 +358,35 @@ bool sd_backend_is(ggml_backend_t backend, const std::string& name) {
return lower_copy(dev_name).find(lower_copy(name)) != std::string::npos;
}
+bool sd_backend_is_amd_vulkan(ggml_backend_dev_t device) {
+ if (device == nullptr)
+ return false;
+ const auto reg = ggml_backend_dev_backend_reg(device);
+ if (reg == nullptr || std::strcmp(ggml_backend_reg_name(reg), "Vulkan") != 0)
+ return false;
+ const char* description = ggml_backend_dev_description(device);
+ if (description == nullptr)
+ return false;
+ const auto name = lower_copy(description);
+ return name.find("amd") != std::string::npos ||
+ name.find("radeon") != std::string::npos ||
+ name.find("radv") != std::string::npos;
+}
+
+ggml_backend_buffer_type_t sd_backend_dev_host_buffer_type(ggml_backend_dev_t device) {
+ if (device == nullptr)
+ return nullptr;
+ auto type = ggml_backend_dev_host_buffer_type(device);
+ if (type != nullptr) {
+ const auto owner = ggml_backend_buft_get_device(type);
+ // ggml's Vulkan host buffers are owned by the first device. Its host import
+ // path is disabled when either the first device or the importing device is AMD.
+ if (owner != device && (sd_backend_is_amd_vulkan(owner) || sd_backend_is_amd_vulkan(device)))
+ return nullptr;
+ }
+ return type;
+}
+
bool sd_backend_is_cuda_family(ggml_backend_t backend) {
const auto dev = backend != nullptr ? ggml_backend_get_device(backend) : nullptr;
const auto reg = dev != nullptr ? ggml_backend_dev_backend_reg(dev) : nullptr;
diff --git a/src/core/ggml_extend_backend.h b/src/core/ggml_extend_backend.h
index 51ee82e..671e2a7 100644
--- a/src/core/ggml_extend_backend.h
+++ b/src/core/ggml_extend_backend.h
@@ -91,6 +91,8 @@ private:
};
bool sd_backend_is(ggml_backend_t backend, const std::string& name);
+bool sd_backend_is_amd_vulkan(ggml_backend_dev_t device);
+ggml_backend_buffer_type_t sd_backend_dev_host_buffer_type(ggml_backend_dev_t device);
bool sd_backend_is_cpu(ggml_backend_t backend);
bool sd_backend_is_cuda_family(ggml_backend_t backend);
bool sd_backend_supports_cuda_mma(ggml_backend_t backend);
diff --git a/src/core/segment_weight_pipeline.cpp b/src/core/segment_weight_pipeline.cpp
index 6c667de..3dccda6 100644
--- a/src/core/segment_weight_pipeline.cpp
+++ b/src/core/segment_weight_pipeline.cpp
@@ -181,10 +181,13 @@ namespace sd {
disable();
return;
}
- switch (manager->prepare_prefetch_params(owner_id_, params, backend_request.prefetch_buffer)) {
+ const auto result = manager->prepare_prefetch_params(owner_id_, params, backend_request.prefetch_buffer);
+ switch (result) {
case WeightPrefetchResult::Scheduled:
- queued_params_ = std::move(params);
- queued_segment_ = next_segment;
+ case WeightPrefetchResult::ScheduledAfterCompute:
+ queued_params_ = std::move(params);
+ queued_segment_ = next_segment;
+ queued_after_compute_ = result == WeightPrefetchResult::ScheduledAfterCompute;
return;
case WeightPrefetchResult::AlreadyResident:
return;
diff --git a/src/core/segment_weight_pipeline.h b/src/core/segment_weight_pipeline.h
index 8791a27..b3f0b83 100644
--- a/src/core/segment_weight_pipeline.h
+++ b/src/core/segment_weight_pipeline.h
@@ -29,8 +29,9 @@ namespace sd {
std::vector<std::vector<ggml_tensor*>> segment_params_;
std::vector<ggml_tensor*> queued_params_;
std::vector<ggml_tensor*> pinned_params_;
- size_t queued_segment_ = SIZE_MAX;
- bool enabled_ = true;
+ size_t queued_segment_ = SIZE_MAX;
+ bool queued_after_compute_ = false;
+ bool enabled_ = true;
size_t next_parameter_segment(size_t segment_index) const;
std::vector<std::vector<ggml_tensor*>> preferred_eviction_order() const;
@@ -58,6 +59,7 @@ namespace sd {
// Prefetch is best effort; segment_start falls back to synchronous loading.
void enqueue_next(size_t segment_index,
const DeviceMemoryRequest& request);
+ bool submit_after_compute() const { return queued_segment_ != SIZE_MAX && queued_after_compute_; }
void submit_next();
};
}
diff --git a/src/device_residency_manager.h b/src/device_residency_manager.h
index ba223fb..e2d8b2f 100644
--- a/src/device_residency_manager.h
+++ b/src/device_residency_manager.h
@@ -20,6 +20,7 @@ namespace sd::weights {
enum class WeightPrefetchResult {
Scheduled,
+ ScheduledAfterCompute,
AlreadyResident,
Unsupported,
Failed,
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index 6a52159..cba1ca8 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -855,8 +855,8 @@ bool ModelManager::cache_merged_lora_weights(const ComputeStagingBlock& block) {
}
// Pinned like offloaded weights, so segment prefetch uploads the cache asynchronously.
auto host_buft = ggml_backend_cpu_buffer_type();
- if (auto device = ggml_backend_get_device(block.compute_backend); device && !sd_backend_is(block.compute_backend, "Vulkan")) {
- if (auto pinned = ggml_backend_dev_host_buffer_type(device))
+ if (auto device = ggml_backend_get_device(block.compute_backend); device && !sd_backend_is_amd_vulkan(device)) {
+ if (auto pinned = sd_backend_dev_host_buffer_type(device))
host_buft = pinned;
}
const size_t bytes = weight_copy_bytes(host_buft, copies);
@@ -1676,11 +1676,10 @@ ggml_backend_buffer_type_t ModelManager::params_buffer_type_for(const TensorStat
ggml_backend_buffer_type_t params_buft = nullptr;
if (state.compute_backend != nullptr && params_backend != state.compute_backend &&
sd_backend_is_cpu(params_backend)) {
- // Vulkan host buffers are driver allocations. Keeping offloaded weights in them
- // can exhaust Vulkan memory even after their device copies have been evicted.
+ // Keeping offloaded weights in Vulkan host buffers can exhaust AMD's GTT.
ggml_backend_dev_t compute_dev = ggml_backend_get_device(state.compute_backend);
- if (compute_dev != nullptr && !sd_backend_is(state.compute_backend, "Vulkan")) {
- params_buft = ggml_backend_dev_host_buffer_type(compute_dev);
+ if (compute_dev != nullptr && !sd_backend_is_amd_vulkan(compute_dev)) {
+ params_buft = sd_backend_dev_host_buffer_type(compute_dev);
}
} else if (params_backend == state.compute_backend) {
params_buft = split_buffer_type_for(state);
diff --git a/src/model_manager_prefetch.cpp b/src/model_manager_prefetch.cpp
index 46c7ec3..69303ee 100644
--- a/src/model_manager_prefetch.cpp
+++ b/src/model_manager_prefetch.cpp
@@ -197,7 +197,7 @@ WeightPrefetchResult ModelManager::prefetch_params(
uintptr_t owner_id,
const std::vector<ggml_tensor*>& tensors) {
auto result = prepare_prefetch_params(owner_id, tensors);
- if (result == WeightPrefetchResult::Scheduled) {
+ if (result == WeightPrefetchResult::Scheduled || result == WeightPrefetchResult::ScheduledAfterCompute) {
submit_prefetched_params(owner_id);
}
return result;
@@ -290,8 +290,15 @@ WeightPrefetchResult ModelManager::prepare_prefetch_params(
free_prefetch_block(*block);
return WeightPrefetchResult::Failed;
}
+ bool submit_after_compute = false;
+ if (sd_backend_is(compute_backend, "Vulkan")) {
+ const auto host_type = sd_backend_dev_host_buffer_type(compute_device);
+ submit_after_compute = std::any_of(block->states.begin(), block->states.end(), [&](const auto* state) {
+ return sd::weights::WeightTransfer::needs_vulkan_staging(*prefetch_source(*block, *state), host_type);
+ });
+ }
prefetch_blocks_[owner_id] = std::move(block);
- return WeightPrefetchResult::Scheduled;
+ return submit_after_compute ? WeightPrefetchResult::ScheduledAfterCompute : WeightPrefetchResult::Scheduled;
}
bool ModelManager::activate_prefetched_params(
diff --git a/src/weights/weight_transfer.cpp b/src/weights/weight_transfer.cpp
index 5524125..6a55213 100644
--- a/src/weights/weight_transfer.cpp
+++ b/src/weights/weight_transfer.cpp
@@ -1,8 +1,36 @@
#include "weights/weight_transfer.h"
+#include <algorithm>
+#include <cstring>
+
+#include "core/ggml_extend_backend.h"
#include "core/util.h"
namespace sd::weights {
+ static TransferEvent record_event(ggml_backend_t queue) {
+ auto event = ggml_backend_event_new(ggml_backend_get_device(queue));
+ if (event == nullptr)
+ return {};
+ TransferEvent result(event, ggml_backend_event_free);
+ ggml_backend_event_record(result.get(), queue);
+ return result;
+ }
+
+ static void wait_event(TransferEvent& event) {
+ if (event) {
+ ggml_backend_event_synchronize(event.get());
+ event.reset();
+ }
+ }
+
+ static void submit_copy(ggml_backend_t queue, const WeightTransfer::Copy& copy) {
+ if (ggml_backend_buffer_is_host(copy.source->buffer)) {
+ ggml_backend_tensor_set_async(queue, copy.destination, copy.source->data, 0, ggml_nbytes(copy.source));
+ } else {
+ ggml_backend_tensor_copy_async(copy.source_backend, queue, const_cast<ggml_tensor*>(copy.source), copy.destination);
+ }
+ }
+
ggml_backend_t WeightTransfer::queue_for(ggml_backend_t compute_backend) {
auto existing = queues_.find(compute_backend);
if (existing != queues_.end())
@@ -23,28 +51,92 @@ namespace sd::weights {
return queue;
}
+ bool WeightTransfer::needs_vulkan_staging(const ggml_tensor& source, ggml_backend_buffer_type_t host_type) {
+ return ggml_backend_buffer_is_host(source.buffer) &&
+ ggml_backend_buffer_get_type(source.buffer) != host_type &&
+ ggml_nbytes(&source) > 0;
+ }
+
+ bool WeightTransfer::submit_vulkan_staged(PendingTransfer& pending, const std::vector<Copy>& copies) {
+ constexpr size_t max_slot_size = 64 * 1024 * 1024;
+ constexpr size_t copy_alignment = 4;
+ const auto device = ggml_backend_get_device(pending.queue);
+ const auto host_type = sd_backend_dev_host_buffer_type(device);
+ if (host_type == nullptr)
+ return false;
+
+ const auto needs_staging = [host_type](const Copy& copy) {
+ return needs_vulkan_staging(*copy.source, host_type);
+ };
+ if (std::none_of(copies.begin(), copies.end(), needs_staging))
+ return false;
+
+ auto [entry, inserted] = vulkan_staging_.try_emplace(device);
+ auto& staging = entry->second;
+ if (inserted) {
+ const size_t capacity = std::min(max_slot_size, ggml_backend_buft_get_max_size(host_type) / staging.events.size());
+ staging.slot_size = capacity - capacity % copy_alignment;
+ if (staging.slot_size > 0) {
+ staging.buffer = ggml_backend_buft_alloc_buffer(host_type, staging.slot_size * staging.events.size());
+ // Vulkan's host allocator can return a pageable CPU buffer on failure.
+ if (staging.buffer && ggml_backend_buffer_get_type(staging.buffer) != host_type) {
+ ggml_backend_buffer_free(staging.buffer);
+ staging.buffer = nullptr;
+ }
+ }
+ }
+ if (staging.buffer == nullptr)
+ return false;
+
+ auto* base = static_cast<char*>(ggml_backend_buffer_get_base(staging.buffer));
+ size_t used = 0;
+ const auto finish_batch = [&]() {
+ auto& event = staging.events[staging.next_slot];
+ event = record_event(pending.queue);
+ if (!event)
+ ggml_backend_synchronize(pending.queue);
+ staging.next_slot = (staging.next_slot + 1) % staging.events.size();
+ used = 0;
+ return event;
+ };
+ for (const auto& copy : copies) {
+ if (!needs_staging(copy)) {
+ submit_copy(pending.queue, copy);
+ continue;
+ }
+ const auto* source = static_cast<const char*>(copy.source->data);
+ const size_t bytes = ggml_nbytes(copy.source);
+ for (size_t offset = 0; offset < bytes;) {
+ const size_t chunk = std::min(bytes - offset, staging.slot_size);
+ if (chunk > staging.slot_size - used)
+ finish_batch();
+ wait_event(staging.events[staging.next_slot]);
+ auto* target = base + staging.next_slot * staging.slot_size + used;
+ std::memcpy(target, source + offset, chunk);
+ ggml_backend_tensor_set_async(pending.queue, copy.destination, target, offset, chunk);
+ used += GGML_PAD(chunk, copy_alignment);
+ offset += chunk;
+ }
+ }
+ // The last batch event protects both the slot and the destination tensors.
+ pending.event = finish_batch();
+ return true;
+ }
+
void WeightTransfer::submit(PendingTransfer& pending, const std::vector<Copy>& copies) {
if (pending.submitted || pending.queue == nullptr)
return;
pending.submitted = true;
- for (const auto& copy : copies) {
- if (ggml_backend_buffer_is_host(copy.source->buffer)) {
- ggml_backend_tensor_set_async(pending.queue, copy.destination, copy.source->data, 0, ggml_nbytes(copy.source));
- } else {
- ggml_backend_tensor_copy_async(copy.source_backend, pending.queue, const_cast<ggml_tensor*>(copy.source),
- copy.destination);
- }
- }
- pending.event = ggml_backend_event_new(ggml_backend_get_device(pending.queue));
- if (pending.event != nullptr)
- ggml_backend_event_record(pending.event, pending.queue);
+ if (sd_backend_is(pending.queue, "Vulkan") && submit_vulkan_staged(pending, copies))
+ return;
+ for (const auto& copy : copies)
+ submit_copy(pending.queue, copy);
+ pending.event = record_event(pending.queue);
}
void WeightTransfer::wait(PendingTransfer& pending) {
- if (pending.event != nullptr) {
- ggml_backend_event_synchronize(pending.event);
- ggml_backend_event_free(pending.event);
- pending.event = nullptr;
+ if (pending.event) {
+ wait_event(pending.event);
} else if (pending.submitted && pending.queue != nullptr) {
ggml_backend_synchronize(pending.queue);
}
@@ -53,6 +145,13 @@ namespace sd::weights {
}
void WeightTransfer::release() {
+ for (auto& [_, staging] : vulkan_staging_) {
+ for (auto& event : staging.events)
+ wait_event(event);
+ if (staging.buffer != nullptr)
+ ggml_backend_buffer_free(staging.buffer);
+ }
+ vulkan_staging_.clear();
for (auto& entry : queues_) {
if (entry.second != nullptr)
ggml_backend_free(entry.second);
diff --git a/src/weights/weight_transfer.h b/src/weights/weight_transfer.h
index 45c36b1..245df96 100644
--- a/src/weights/weight_transfer.h
+++ b/src/weights/weight_transfer.h
@@ -1,18 +1,22 @@
#ifndef __SD_WEIGHTS_WEIGHT_TRANSFER_H__
#define __SD_WEIGHTS_WEIGHT_TRANSFER_H__
+#include <array>
#include <map>
+#include <memory>
#include <set>
#include <vector>
#include "ggml-backend.h"
namespace sd::weights {
+ using TransferEvent = std::shared_ptr<ggml_backend_event>;
+
// Uploads that run on a compute device's transfer queue while it computes.
struct PendingTransfer {
- ggml_backend_t queue = nullptr;
- ggml_backend_event_t event = nullptr;
- bool submitted = false;
+ ggml_backend_t queue = nullptr;
+ TransferEvent event;
+ bool submitted = false;
};
// Asynchronous weight uploads. The residency layer chooses the copies and owns their buffers;
@@ -33,6 +37,7 @@ namespace sd::weights {
// The transfer queue of a compute device; null when the device has none.
ggml_backend_t queue_for(ggml_backend_t compute_backend);
+ static bool needs_vulkan_staging(const ggml_tensor& source, ggml_backend_buffer_type_t host_type);
// Queues the copies on pending.queue and records their completion.
void submit(PendingTransfer& pending, const std::vector<Copy>& copies);
// Waits for submitted copies; pending can be reused afterwards.
@@ -40,8 +45,18 @@ namespace sd::weights {
void release();
private:
+ struct VulkanStaging {
+ ggml_backend_buffer_t buffer = nullptr;
+ std::array<TransferEvent, 2> events;
+ size_t slot_size = 0;
+ size_t next_slot = 0;
+ };
+
std::map<ggml_backend_t, ggml_backend_t> queues_;
std::set<ggml_backend_t> failed_;
+ std::map<ggml_backend_dev_t, VulkanStaging> vulkan_staging_;
+
+ bool submit_vulkan_staged(PendingTransfer& pending, const std::vector<Copy>& copies);
};
}