Commit da1c031 for stable-diffusion.cpp
commit da1c031c0b1b0d3c4ee1a8fdfaa124be8eb8c723
Author: leejet <leejet714@gmail.com>
Date: Mon Dec 7 00:46:46 2026 +0800
perf: reduce MiniMax H3 VRAM usage with adaptive token tiling (#2541)
diff --git a/src/core/alloc_status.h b/src/core/alloc_status.h
new file mode 100644
index 0000000..f8a1a5a
--- /dev/null
+++ b/src/core/alloc_status.h
@@ -0,0 +1,17 @@
+#ifndef __SD_CORE_ALLOC_STATUS_H__
+#define __SD_CORE_ALLOC_STATUS_H__
+
+#include "ggml-backend.h"
+
+namespace sd {
+ enum class AllocStatus {
+ Success,
+ Failed,
+ AllocFailed,
+ DeviceAllocFailed,
+ };
+
+ AllocStatus backend_alloc_failure(ggml_backend_t backend);
+}
+
+#endif // __SD_CORE_ALLOC_STATUS_H__
diff --git a/src/core/compute_workspace.cpp b/src/core/compute_workspace.cpp
index 9b01c3d..9450cf2 100644
--- a/src/core/compute_workspace.cpp
+++ b/src/core/compute_workspace.cpp
@@ -12,6 +12,32 @@
#include "core/util.h"
namespace sd {
+ struct MeasurementGraph {
+ ggml_context* context = nullptr;
+ std::map<std::pair<ggml_backend_t, const void*>, ggml_backend_buffer_t> external_buffers;
+
+ ~MeasurementGraph() {
+ for (const auto& entry : external_buffers) {
+ ggml_backend_buffer_free(entry.second);
+ }
+ ggml_free(context);
+ }
+ };
+
+ struct ComputeWorkspace::MeasurementScheduler {
+ ggml_backend_sched_t scheduler;
+ size_t capacity;
+ std::unique_ptr<MeasurementGraph> graph;
+
+ MeasurementScheduler(ggml_backend_sched_t scheduler, size_t capacity)
+ : scheduler(scheduler), capacity(capacity) {}
+
+ ~MeasurementScheduler() { ggml_backend_sched_free(scheduler); }
+ };
+
+ ComputeWorkspace::ComputeWorkspace(ggml_backend_t backend)
+ : backend_(backend) {}
+
ComputeWorkspace::~ComputeWorkspace() {
segment_end();
release();
@@ -64,6 +90,10 @@ namespace sd {
// The reported size includes per-graph scratch, which can shrink while the scheduler is retained.
for (size_t i = 0; i < peak_scheduler_bytes_.size(); ++i) {
if (measurement.buffers[i].bytes > peak_scheduler_bytes_[i]) {
+ LOG_DEBUG("releasing workspace to grow %s from %.2f to %.2f MiB",
+ ggml_backend_name(measurement.buffers[i].backend),
+ peak_scheduler_bytes_[i] / (1024.0 * 1024.0),
+ measurement.buffers[i].bytes / (1024.0 * 1024.0));
return release_scheduler();
}
}
@@ -71,21 +101,41 @@ namespace sd {
}
bool ComputeWorkspace::release_excess(const Measurement& measurement) {
- return std::any_of(measurement.buffers.begin(), measurement.buffers.end(),
- [&](const BackendBufferSize& size) { return bytes(size.backend) > size.bytes; }) &&
- release_scheduler();
+ if (active_) {
+ return false;
+ }
+ for (const auto& size : measurement.buffers) {
+ const size_t retained = bytes(size.backend);
+ if (retained > size.bytes) {
+ LOG_DEBUG("releasing workspace to fit the memory budget on %s (retained %.2f MiB, required %.2f MiB)",
+ ggml_backend_name(size.backend), retained / (1024.0 * 1024.0), size.bytes / (1024.0 * 1024.0));
+ return release_scheduler();
+ }
+ }
+ return false;
}
- bool ComputeWorkspace::allocate(ggml_cgraph* graph, const Measurement& measurement, const AssignNodes& assign_nodes, const CheckHostMemory& ensure_host_memory) {
+ AllocStatus 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_) {
+ if (scheduler_ != nullptr) {
+ LOG_DEBUG("releasing workspace to grow scheduler capacity from %zu to %zu tensors", scheduler_capacity_, capacity);
+ }
release_scheduler();
- scheduler_ = make_scheduler(capacity, ensure_host_memory);
- scheduler_capacity_ = capacity;
+ // Retain enough host metadata for the largest segment seen before a workspace trim.
+ size_t reserved_capacity = std::max(capacity, scheduler_capacity_);
+ scheduler_ = make_scheduler(reserved_capacity, ensure_host_memory);
+ if (scheduler_ == nullptr && reserved_capacity > capacity) {
+ reserved_capacity = capacity;
+ scheduler_ = make_scheduler(reserved_capacity, ensure_host_memory);
+ }
+ if (scheduler_ != nullptr) {
+ scheduler_capacity_ = reserved_capacity;
+ }
}
if (scheduler_ == nullptr) {
- return false;
+ return AllocStatus::AllocFailed;
}
size_t host_bytes = 0;
for (const auto& size : measurement.buffers) {
@@ -95,20 +145,20 @@ namespace sd {
}
}
if (ensure_host_memory && !ensure_host_memory(host_bytes, false))
- return false;
+ return AllocStatus::AllocFailed;
ggml_backend_sched_reset(scheduler_);
assign_nodes(scheduler_, graph);
// Scheduler allocation rewrites sources. Split the execution graph only once.
if (!ggml_backend_sched_alloc_graph(scheduler_, graph)) {
release();
- return false;
+ return backend_alloc_failure(backend_);
}
peak_scheduler_bytes_.resize(measurement.buffers.size());
for (size_t i = 0; i < measurement.buffers.size(); ++i) {
peak_scheduler_bytes_[i] = std::max(peak_scheduler_bytes_[i], bytes(measurement.buffers[i].backend));
}
active_ = true;
- return true;
+ return AllocStatus::Success;
}
ComputeWorkspace::Measurement ComputeWorkspace::measure(
@@ -116,6 +166,7 @@ namespace sd {
const std::function<ggml_backend_t(const ggml_tensor*)>& external_backend,
const AssignNodes& assign_nodes,
bool cache_measurement,
+ bool reuse_scheduler,
const CheckHostMemory& ensure_host_memory) {
std::vector<const ggml_tensor*> tensors;
std::unordered_set<const ggml_tensor*> seen;
@@ -187,12 +238,13 @@ namespace sd {
}
}
const size_t graph_size = tensors.size() + 8;
+ auto shadow = std::make_unique<MeasurementGraph>();
auto context = ggml_init({tensors.size() * ggml_tensor_overhead() + ggml_graph_overhead_custom(graph_size, false), nullptr, true});
+ shadow->context = context;
if (context == nullptr) {
return {};
}
std::unordered_map<const ggml_tensor*, ggml_tensor*> copies;
- std::map<std::pair<ggml_backend_t, const void*>, ggml_backend_buffer_t> external_buffers;
for (auto tensor : tensors) {
auto copy = ggml_dup_tensor(context, tensor);
*copy = *tensor;
@@ -209,7 +261,7 @@ namespace sd {
if (external != nullptr && source->view_src == nullptr) {
// Preserve distinct external allocations so overlap checks do not invent aliases.
const void* storage = source->buffer ? static_cast<const void*>(source->buffer) : source;
- auto& buffer = external_buffers[{external, storage}];
+ auto& buffer = shadow->external_buffers[{external, storage}];
if (buffer == nullptr) {
buffer = ggml_backend_alloc_buffer(external, 0);
GGML_ASSERT(buffer != nullptr);
@@ -240,22 +292,34 @@ namespace sd {
return found == mapped.end() ? nullptr : found->second;
};
GGML_ASSERT(ggml_graph_cpy_mapped(graph, copy_graph, map_tensor, &copies));
- Measurement result;
- auto scheduler = make_scheduler(graph_size, ensure_host_memory);
- if (scheduler != nullptr) {
- assign_nodes(scheduler, copy_graph);
- std::vector<size_t> sizes(extra_backends_.size() + 2);
- ggml_backend_sched_reserve_size(scheduler, copy_graph, sizes.data());
- result.buffers.push_back({backend_, sizes[0]});
- for (size_t i = 0; i < extra_backends_.size(); ++i) {
- result.buffers.push_back({extra_backends_[i], sizes[i + 1]});
+ std::unique_ptr<MeasurementScheduler> temporary;
+ auto& measurement = reuse_scheduler ? measurement_ : temporary;
+ if (!measurement || graph_size > measurement->capacity) {
+ measurement.reset();
+ measurement = std::make_unique<MeasurementScheduler>(nullptr, graph_size);
+ measurement->scheduler = make_scheduler(graph_size, ensure_host_memory);
+ if (measurement->scheduler == nullptr) {
+ measurement.reset();
+ return {};
}
- ggml_backend_sched_free(scheduler);
}
- for (const auto& entry : external_buffers) {
- ggml_backend_buffer_free(entry.second);
+ auto scheduler = measurement->scheduler;
+ ggml_backend_sched_reset(scheduler);
+ assign_nodes(scheduler, copy_graph);
+ std::vector<size_t> sizes(extra_backends_.size() + 2);
+ try {
+ ggml_backend_sched_reserve_size(scheduler, copy_graph, sizes.data());
+ } catch (...) {
+ measurement.reset();
+ throw;
+ }
+ // Reserve releases the previous plans, which can refer to the previous graph.
+ measurement->graph = std::move(shadow);
+ Measurement result;
+ result.buffers.push_back({backend_, sizes[0]});
+ for (size_t i = 0; i < extra_backends_.size(); ++i) {
+ result.buffers.push_back({extra_backends_[i], sizes[i + 1]});
}
- ggml_free(context);
if (cache_measurement && !result.buffers.empty()) {
measurement_cache_.back() = std::move(measurement_cache_.front());
measurement_cache_.front() = {std::move(key), result.buffers};
@@ -294,6 +358,8 @@ namespace sd {
if (!release_scheduler()) {
return false;
}
+ scheduler_capacity_ = 0;
+ measurement_.reset();
measurement_cache_ = {};
return true;
}
@@ -318,8 +384,7 @@ namespace sd {
}
ggml_backend_sched_free(scheduler_);
}
- scheduler_ = nullptr;
- scheduler_capacity_ = 0;
+ scheduler_ = nullptr;
peak_scheduler_bytes_.clear();
return true;
}
diff --git a/src/core/compute_workspace.h b/src/core/compute_workspace.h
index c566b8c..7548b70 100644
--- a/src/core/compute_workspace.h
+++ b/src/core/compute_workspace.h
@@ -3,8 +3,10 @@
#include <array>
#include <functional>
+#include <memory>
#include <vector>
+#include "core/alloc_status.h"
#include "ggml-backend.h"
namespace sd {
@@ -28,6 +30,8 @@ namespace sd {
std::vector<BackendBufferSize> buffers;
};
std::array<CachedMeasurement, 2> measurement_cache_;
+ struct MeasurementScheduler;
+ std::unique_ptr<MeasurementScheduler> measurement_;
ggml_backend_sched_t make_scheduler(size_t graph_size, const CheckHostMemory& ensure_host_memory);
bool release_scheduler();
@@ -38,8 +42,7 @@ namespace sd {
};
using AssignNodes = std::function<void(ggml_backend_sched_t, ggml_cgraph*)>;
- explicit ComputeWorkspace(ggml_backend_t backend)
- : backend_(backend) {}
+ explicit ComputeWorkspace(ggml_backend_t backend);
~ComputeWorkspace();
ComputeWorkspace(const ComputeWorkspace&) = delete;
ComputeWorkspace& operator=(const ComputeWorkspace&) = delete;
@@ -47,13 +50,14 @@ 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 CheckHostMemory& ensure_host_memory = {});
+ AllocStatus 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 CheckHostMemory& ensure_host_memory = {});
+ bool cache_measurement,
+ bool reuse_scheduler,
+ 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 0da8bb2..1d02287 100644
--- a/src/core/execution_engine.cpp
+++ b/src/core/execution_engine.cpp
@@ -36,6 +36,7 @@ namespace sd {
ggml_status last_compute_status_ = GGML_STATUS_FAILED;
Tensor<float> output_;
std::string device_memory_error_;
+ AllocStatus failure_ = AllocStatus::Failed;
using GraphCutPlan = ggml_graph_cut::Plan;
ggml_tensor* canonical_param_tensor(ggml_tensor* tensor);
@@ -54,6 +55,11 @@ namespace sd {
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(); }
+ void record_failure(AllocStatus status) {
+ GGML_ASSERT(status != AllocStatus::Success);
+ failure_ = status;
+ last_compute_status_ = status == AllocStatus::Failed ? GGML_STATUS_FAILED : GGML_STATUS_ALLOC_FAILED;
+ }
size_t retained_runtime_buffer_bytes(ggml_backend_t backend) const { return session_.resident_bytes(backend); }
void sync_runtime_residency() { engine_.sync_residency(session_); }
@@ -79,9 +85,9 @@ namespace sd {
ComputeResult run() {
if (!execute_graph(task_.graph, task_.n_threads, task_.no_return, task_.read_outputs)) {
- return {last_compute_status_, {}, std::move(device_memory_error_)};
+ return {last_compute_status_, {}, std::move(device_memory_error_), failure_};
}
- return {GGML_STATUS_SUCCESS, std::move(output_), {}};
+ return {GGML_STATUS_SUCCESS, std::move(output_), {}, AllocStatus::Success};
}
};
@@ -412,9 +418,12 @@ 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, bool require_available) {
+ auto ensure_host_memory = [&](size_t bytes, bool require_available) {
return manager_ == nullptr || manager_->ensure_host_memory(bytes, task_.weights, 0, require_available);
- });
+ };
+ // Whole-graph probes can be much larger than any segment that will actually run.
+ return session_.workspace_.measure(graph, external_backend, assign_nodes, !is_multi_device(),
+ external_outputs != nullptr, ensure_host_memory);
}
std::vector<DeviceMemoryRequest> GraphExecution::memory_requests(
@@ -555,8 +564,7 @@ namespace sd {
const auto params = collect_used_param_tensors(graph);
const auto& cached_plan = resolve_graph_cut_plan(graph);
auto manager = manager_;
- const bool can_segment = !is_multi_device() && !sd_backend_is_cpu(session_.backend_) &&
- session_.segmented_compute_ &&
+ const bool can_segment = session_.can_segment_graph() && !sd_backend_is_cpu(session_.backend_) &&
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, DeviceMemoryCheck::Reclaimable);
@@ -627,7 +635,7 @@ namespace sd {
auto fail_segment = [&](const char* phase) {
auto message = sd_format("%s segment %zu/%zu (%s) failed during %s", task_.description.c_str(),
index + 1, plan.segments.size(), segment.group_name.c_str(), phase);
- if (task_.capacity_failure_recoverable && !device_memory_error_.empty())
+ if (task_.capacity_failure_recoverable && failure_ == AllocStatus::DeviceAllocFailed)
LOG_INFO("%s", message.c_str());
else
LOG_ERROR("%s", message.c_str());
@@ -653,6 +661,7 @@ namespace sd {
~SegmentCleanup() {
if (!runner.session_.workspace_.segment_end()) {
runner.last_compute_status_ = GGML_STATUS_FAILED;
+ runner.failure_ = AllocStatus::Failed;
}
bindings.restore();
weights.segment_end();
@@ -690,27 +699,25 @@ namespace sd {
}
}
if (fits(requests, weights.params(index), DeviceMemoryCheck::Inspect)) {
- return true;
+ return AllocStatus::Success;
}
// Shrinking the retained workspace is the last resort; later segments regrow it.
auto quiet_requests = requests;
for (auto& request : quiet_requests) {
request.quiet = true;
}
- if (weights.ensure_segment_capacity(index, quiet_requests, nullptr)) {
- return true;
+ if (weights.ensure_segment_capacity(index, quiet_requests, nullptr) == AllocStatus::Success) {
+ return AllocStatus::Success;
}
if (session_.workspace_.release_excess(measurement)) {
sync_runtime_residency();
requests = memory_requests(measurement.buffers, new_cache_bytes);
}
- const bool ready = weights.ensure_segment_capacity(index, requests, &device_memory_error_);
- if (!ready && manager != nullptr) {
- last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
- }
- return ready;
+ return weights.ensure_segment_capacity(index, requests, &device_memory_error_);
};
- if (!weights.segment_start(index, ensure_capacity)) {
+ const auto prepared = weights.segment_start(index, ensure_capacity);
+ if (prepared != AllocStatus::Success) {
+ record_failure(prepared);
return fail_segment("weight preparation");
}
segment_progress.weights_ready(index + 1);
@@ -719,11 +726,14 @@ namespace sd {
last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
return fail_segment("workspace preparation");
}
- if (!ensure_capacity()) {
+ const auto capacity = ensure_capacity();
+ if (capacity != AllocStatus::Success) {
+ record_failure(capacity);
return fail_segment("workspace capacity check");
}
- if (!session_.cut_cache_.bind_outputs(cache_outputs)) {
- last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
+ const auto bound = session_.cut_cache_.bind_outputs(cache_outputs);
+ if (bound != AllocStatus::Success) {
+ record_failure(bound);
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));
@@ -741,9 +751,11 @@ namespace sd {
#endif
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)) {
- last_compute_status_ = GGML_STATUS_ALLOC_FAILED;
+ const auto allocated = session_.workspace_.allocate(
+ segment_graph, measurement, [&](ggml_backend_sched_t scheduler, ggml_cgraph* current) { pin_multi_device_nodes(scheduler, current); },
+ ensure_host_memory);
+ if (allocated != AllocStatus::Success) {
+ record_failure(allocated);
return fail_segment("workspace allocation");
}
for (const auto& size : measurement.buffers) {
@@ -752,7 +764,9 @@ namespace sd {
if (session_.workspace_.scheduler() != nullptr) {
track_compute_buffer(session_.workspace_.cpu_backend());
}
- if (!ensure_capacity()) {
+ const auto allocated_capacity = ensure_capacity();
+ if (allocated_capacity != AllocStatus::Success) {
+ record_failure(allocated_capacity);
return fail_segment("allocated capacity check");
}
copy_data_to_backend_tensor(segment_graph);
@@ -766,11 +780,11 @@ namespace sd {
return fail_segment("execution");
}
auto cache_status = session_.cache_.capture(segment_graph);
- if (cache_status == GGML_STATUS_SUCCESS) {
+ if (cache_status == AllocStatus::Success) {
cache_status = session_.cut_cache_.capture(graph, segment, task_.description.c_str());
}
- if (cache_status != GGML_STATUS_SUCCESS) {
- last_compute_status_ = cache_status;
+ if (cache_status != AllocStatus::Success) {
+ record_failure(cache_status);
return fail_segment("output caching");
}
sync_runtime_residency();
@@ -928,7 +942,7 @@ namespace sd {
}
}
- bool ExecutionEngine::ensure_capacity(
+ AllocStatus ExecutionEngine::ensure_capacity(
DeviceResidencyManager& manager,
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
@@ -946,10 +960,10 @@ namespace sd {
};
const auto initial = capacity();
if (!initial.valid) {
- return false;
+ return AllocStatus::Failed;
}
if (initial.fits()) {
- return true;
+ return AllocStatus::Success;
}
// Weight copies go first: a copy demoted once is cheap to drop later, while compute
// buffers are reused by every graph.
@@ -958,7 +972,7 @@ namespace sd {
protected_weights.insert(protected_weights.end(), required_params.begin(), required_params.end());
for (const auto& block : candidates) {
if (manager.evict_compute_backend_block(block, prefetch_buffer, &protected_weights) && capacity().fits(true)) {
- return true;
+ return AllocStatus::Success;
}
}
for (auto& entry : sessions_) {
@@ -966,13 +980,13 @@ namespace sd {
if (session.owner_id() != request.owner_id && !session.executing_ && session.workspace_.release()) {
sync_residency(session);
if (capacity().fits(true)) {
- return true;
+ return AllocStatus::Success;
}
}
}
auto available = capacity();
if (available.fits(true)) {
- return true;
+ return AllocStatus::Success;
}
if (sd_backend_is(request.compute_backend, "Vulkan") && available.fits_budget()) {
ggml_backend_synchronize(request.compute_backend);
@@ -981,7 +995,7 @@ namespace sd {
do {
available = capacity();
if (available.fits(true)) {
- return true;
+ return AllocStatus::Success;
}
if (!available.fits_budget()) {
break;
@@ -990,12 +1004,15 @@ namespace sd {
} while (std::chrono::steady_clock::now() < deadline);
}
if (request.quiet) {
- return false;
+ return available.valid ? backend_alloc_failure(request.compute_backend) : AllocStatus::Failed;
}
available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect,
!request.recoverable);
+ if (!available.valid) {
+ return AllocStatus::Failed;
+ }
if (available.fits(true))
- return true;
+ return AllocStatus::Success;
const bool budget_allows = available.fits_budget();
const auto device_bytes = available.available_device_bytes == SIZE_MAX
? std::string("unknown")
@@ -1009,16 +1026,16 @@ namespace sd {
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;
+ return AllocStatus::Success;
}
if (request.recoverable)
LOG_INFO("%s", message.c_str());
else
LOG_WARN("%s", message.c_str());
- if (device_memory_error != nullptr && available.valid) {
+ if (device_memory_error != nullptr) {
*device_memory_error = std::move(message);
}
- return false;
+ return backend_alloc_failure(request.compute_backend);
}
void ExecutionEngine::trim_buffer_pool(const DeviceResidencyManager& manager,
@@ -1120,7 +1137,8 @@ namespace sd {
ggml_backend_name(session.backend_));
}
if (!session.workspace_.segment_end()) {
- result.status = GGML_STATUS_FAILED;
+ result.status = GGML_STATUS_FAILED;
+ result.failure = AllocStatus::Failed;
}
const bool success = result.status == GGML_STATUS_SUCCESS;
session.cache_.graph_end(success);
diff --git a/src/core/execution_engine.h b/src/core/execution_engine.h
index 18b5263..47f0f81 100644
--- a/src/core/execution_engine.h
+++ b/src/core/execution_engine.h
@@ -37,6 +37,7 @@ namespace sd {
ggml_status status = GGML_STATUS_FAILED;
Tensor<float> output;
std::string device_memory_error;
+ AllocStatus failure = AllocStatus::Failed;
};
class ExecutionSession {
@@ -74,7 +75,9 @@ namespace sd {
RunnerCache& cache() { return cache_; }
bool started() const { return started_; }
+ bool can_segment_graph() const { return segmented_compute_ && extra_backends_.empty(); }
size_t compute_bytes() const { return workspace_.bytes(backend_); }
+ size_t max_backend_bytes() const { return max_backend_bytes_; }
void clear_plan_cache() { plan_cache_.graph_cut_plans.clear(); }
void set_max_backend_bytes(size_t bytes) { max_backend_bytes_ = bytes; }
void set_layer_split_enabled(bool enabled);
@@ -100,19 +103,20 @@ namespace sd {
void end(ExecutionSession& session);
void clear_cache(ExecutionSession& session);
void discard_graph(ExecutionSession& session);
- bool ensure_capacity(DeviceResidencyManager& manager,
+ AllocStatus ensure_capacity(DeviceResidencyManager& manager,
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error = nullptr);
- bool reserve(const DeviceMemoryRequest& request,
+ AllocStatus reserve(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error) override {
- return manager_ && ensure_capacity(*manager_, request, required_params, preferred_eviction_order, protected_params,
- device_memory_error);
+ return manager_ ? ensure_capacity(*manager_, request, required_params, preferred_eviction_order, protected_params,
+ device_memory_error)
+ : AllocStatus::Failed;
}
// Graphs, input data and output callbacks remain borrowed until execute returns.
ComputeResult execute(ExecutionSession& session, const ComputeTask& task);
diff --git a/src/core/ggml_extend.cpp b/src/core/ggml_extend.cpp
index 99d5f64..0aeaf5d 100644
--- a/src/core/ggml_extend.cpp
+++ b/src/core/ggml_extend.cpp
@@ -1,6 +1,7 @@
#include "core/ggml_extend.h"
#include <cmath>
+#include <memory>
#include <stdexcept>
#include <utility>
#include <vector>
@@ -827,6 +828,124 @@ ggml_tensor* ggml_ext_attention_ext(GGMLRunnerContext* runner_ctx,
return kqv;
}
+static GGMLAttentionKV make_tiled_kv(ggml_context* c, int64_t inner, int64_t tokens, int64_t batch) {
+ return {ggml_new_tensor_3d(c, GGML_TYPE_F16, inner, tokens, batch),
+ ggml_new_tensor_3d(c, GGML_TYPE_F16, inner, tokens, batch)};
+}
+
+static GGMLAttentionKV tiled_kv_views(ggml_context* c, GGMLAttentionKV kv, int64_t head_dim, int64_t heads) {
+ auto view = [&](ggml_tensor* rows) {
+ return ggml_permute(c, ggml_reshape_4d(c, rows, head_dim, heads, rows->ne[1], rows->ne[2]), 0, 2, 1, 3);
+ };
+ return {view(kv.key), view(kv.value)};
+}
+
+static GGMLAttentionKV write_tiled_kv(ggml_context* c, GGMLAttentionKV kv, GGMLAttentionKV update, ggml_tensor* indices) {
+ return {ggml_set_rows(c, kv.key, update.key, indices), ggml_set_rows(c, kv.value, update.value, indices)};
+}
+
+static ggml_tensor* attend_tiled_query(ggml_context* c, ggml_tensor* q, GGMLAttentionKV kv, float scale) {
+ auto attention = ggml_flash_attn_ext(c, q, kv.key, kv.value, nullptr, scale, 0.f, 0.f);
+ ggml_prec_set_acc(attention, GGML_PREC_F32);
+ return attention;
+}
+
+bool ggml_ext_supports_tiled_flash_attention(ggml_backend_t backend,
+ int64_t head_dim,
+ int64_t heads,
+ int64_t tokens,
+ int64_t batch,
+ const std::vector<int64_t>& tile_lengths) {
+ if (backend == nullptr || sd_backend_is_cpu(backend) || head_dim <= 0 || heads <= 0 ||
+ tokens <= 0 || batch <= 0 || tile_lengths.empty()) {
+ return false;
+ }
+ const auto tensors = 6 + 6 * tile_lengths.size();
+ const std::unique_ptr<ggml_context, decltype(&ggml_free)> context(
+ ggml_init({tensors * ggml_tensor_overhead(), nullptr, true}), ggml_free);
+ auto c = context.get();
+ if (c == nullptr) {
+ return false;
+ }
+
+ const int64_t inner = heads * head_dim;
+ const auto storage = make_tiled_kv(c, inner, tokens, batch);
+ const auto kv = tiled_kv_views(c, storage, head_dim, heads);
+ for (int64_t rows : tile_lengths) {
+ if (rows <= 0 || rows > tokens) {
+ return false;
+ }
+ auto indices = ggml_new_tensor_1d(c, GGML_TYPE_I32, rows);
+ auto update = ggml_new_tensor_3d(c, GGML_TYPE_F32, inner, rows, batch);
+ auto written = write_tiled_kv(c, storage, {update, update}, indices);
+ auto q = ggml_new_tensor_4d(c, GGML_TYPE_F32, head_dim, rows, heads, batch);
+ auto attention = attend_tiled_query(c, q, kv, 1.f);
+ if (!ggml_backend_supports_op(backend, written.key) || !ggml_backend_supports_op(backend, written.value) ||
+ !ggml_backend_supports_op(backend, attention)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void ggml_ext_flash_attention_tiled(
+ GGMLRunnerContext* ctx,
+ const std::vector<ggml_tensor*>& inputs,
+ ggml_tensor* token_indices,
+ int64_t head_dim,
+ int64_t heads,
+ int64_t tile_rows,
+ float kv_scale,
+ const std::function<GGMLAttentionKV(const GGMLAttentionTile&)>& project_kv,
+ const std::function<ggml_tensor*(const GGMLAttentionTile&)>& project_query,
+ const std::function<ggml_tensor*(const GGMLAttentionTile&, ggml_tensor*)>& consume_output) {
+ GGML_ASSERT(ctx->graph != nullptr && !inputs.empty() && token_indices != nullptr);
+ GGML_ASSERT(ggml_is_vector(token_indices) && head_dim > 0 && heads > 0 && kv_scale > 0.f);
+ auto c = ctx->ggml_ctx;
+ const int64_t tokens = token_indices->ne[0];
+ const int64_t batch = inputs.front()->ne[2];
+ const int64_t inner = heads * head_dim;
+ kv_scale = ctx->attn_scale > 0.f ? ctx->attn_scale : kv_scale;
+ const float scale = (1.f / std::sqrt(static_cast<float>(head_dim))) / kv_scale;
+
+ auto for_each_tile = [&](const auto& visit) {
+ int64_t offset = 0;
+ for (size_t i = 0; i < inputs.size(); ++i) {
+ auto input = inputs[i];
+ GGML_ASSERT(input->ne[2] == batch && input->ne[3] == 1);
+ ggml_ext_for_each_token_tile(ctx, input, 0, input->ne[1], tile_rows, true,
+ [&](ggml_tensor* part, int64_t start, int64_t stop) {
+ auto indices = ggml_ext_slice(ctx, token_indices, 0, offset + start, offset + stop, false);
+ visit(GGMLAttentionTile{part, i, offset + start, indices});
+ });
+ offset += input->ne[1];
+ }
+ GGML_ASSERT(offset == tokens);
+ };
+
+ // Write projection tiles straight into the FP16 K/V that Flash Attention reads.
+ auto storage = make_tiled_kv(c, inner, tokens, batch);
+ for_each_tile([&](const GGMLAttentionTile& tile) {
+ const auto kv = project_kv(tile);
+ const int64_t length = tile.input->ne[1];
+ auto key = ggml_cont(c, ggml_permute(c, kv.key, 0, 2, 1, 3));
+ key = ggml_reshape_3d(c, key, inner, length, batch);
+ auto value = ggml_reshape_3d(c, ggml_ext_cont(ctx, kv.value), inner, length, batch);
+ storage = write_tiled_kv(c, storage, {ggml_ext_scale(ctx, key, kv_scale), ggml_ext_scale(ctx, value, kv_scale)}, tile.indices);
+ ctx->expand_graph(storage.key);
+ ctx->expand_graph(storage.value);
+ });
+ const auto kv = tiled_kv_views(c, storage, head_dim, heads);
+
+ for_each_tile([&](const GGMLAttentionTile& tile) {
+ auto q = project_query(tile);
+ auto output = attend_tiled_query(c, q, kv, scale);
+ output = ggml_ext_scale(ctx, output, 1.f / kv_scale);
+ output = ggml_reshape_3d(c, output, inner, tile.input->ne[1], batch);
+ ctx->expand_graph(consume_output(tile, output));
+ });
+}
+
ggml_tensor* ggml_ext_layer_norm(GGMLRunnerContext* runner_ctx,
ggml_tensor* x,
ggml_tensor* w,
diff --git a/src/core/ggml_extend.h b/src/core/ggml_extend.h
index 61f8324..6fe93db 100644
--- a/src/core/ggml_extend.h
+++ b/src/core/ggml_extend.h
@@ -1,7 +1,9 @@
#ifndef __SD_CORE_GGML_EXTEND_H__
#define __SD_CORE_GGML_EXTEND_H__
+#include <algorithm>
#include <cstdint>
+#include <functional>
#include <vector>
#include "core/ggml_extensions.h"
@@ -34,6 +36,17 @@ ggml_tensor* ggml_ext_slice(GGMLRunnerContext* runner_ctx,
int64_t end,
bool cont = true);
+// Keep a producer and its tile-local consumers together up to their final write.
+template <typename Visit>
+void ggml_ext_for_each_token_tile(GGMLRunnerContext* ctx, ggml_tensor* input, int64_t begin, int64_t end, int64_t rows, bool contiguous, Visit&& visit) {
+ GGML_ASSERT(rows > 0 && begin >= 0 && begin <= end && end <= input->ne[1]);
+ for (int64_t start = begin; start < end;) {
+ const int64_t stop = start + std::min(rows, end - start);
+ visit(ggml_ext_slice(ctx, input, 1, start, stop, contiguous), start, stop);
+ start = stop;
+ }
+}
+
// example: [N, 3*C, H, W] => ([N, C, H, W], [N, C, H, W], [N, C, H, W])
std::vector<ggml_tensor*> ggml_ext_chunk(GGMLRunnerContext* runner_ctx,
ggml_tensor* x,
@@ -184,6 +197,44 @@ ggml_tensor* ggml_ext_attention_ext(GGMLRunnerContext* runner_ctx,
float kv_scale = 1.0f,
bool* used_flash_attn = nullptr);
+struct GGMLAttentionTile {
+ ggml_tensor* input; // contiguous rows of inputs[input_index]
+ size_t input_index;
+ int64_t sequence_offset;
+ ggml_tensor* indices; // token_indices for these rows
+};
+
+struct GGMLAttentionKV {
+ ggml_tensor* key;
+ ggml_tensor* value;
+};
+
+// Probe the actual K/V storage and query tile shapes.
+bool ggml_ext_supports_tiled_flash_attention(ggml_backend_t backend,
+ int64_t head_dim,
+ int64_t heads,
+ int64_t tokens,
+ int64_t batch,
+ const std::vector<int64_t>& tile_lengths);
+
+// Dense self-attention on backends where ggml_ext_supports_tiled_flash_attention holds.
+// Input spans are consecutive [features, tokens, batch] tensors. token_indices
+// is a vector of consecutive row indices starting at zero. In GGML dimension order, the
+// projection callbacks return F32 Q/K as [head_dim, tokens, heads, batch] and V as
+// [head_dim, heads, tokens, batch]. The consumer receives [head_dim * heads,
+// tokens, batch] and returns its final node to schedule before the next tile.
+void ggml_ext_flash_attention_tiled(
+ GGMLRunnerContext* ctx,
+ const std::vector<ggml_tensor*>& inputs,
+ ggml_tensor* token_indices,
+ int64_t head_dim,
+ int64_t heads,
+ int64_t tile_rows,
+ float kv_scale,
+ const std::function<GGMLAttentionKV(const GGMLAttentionTile&)>& project_kv,
+ const std::function<ggml_tensor*(const GGMLAttentionTile&)>& project_query,
+ const std::function<ggml_tensor*(const GGMLAttentionTile&, ggml_tensor*)>& consume_output);
+
ggml_tensor* ggml_ext_layer_norm(GGMLRunnerContext* runner_ctx,
ggml_tensor* x,
ggml_tensor* w,
diff --git a/src/core/ggml_extend_backend.cpp b/src/core/ggml_extend_backend.cpp
index 863054f..3daed62 100644
--- a/src/core/ggml_extend_backend.cpp
+++ b/src/core/ggml_extend_backend.cpp
@@ -1,4 +1,6 @@
#include "core/ggml_extend_backend.h"
+
+#include "core/alloc_status.h"
#include "core/ggml_extensions.h"
#include <algorithm>
@@ -533,6 +535,13 @@ bool sd_backend_is_cpu(ggml_backend_t backend) {
return it->second;
}
+sd::AllocStatus sd::backend_alloc_failure(ggml_backend_t backend) {
+ if (backend == nullptr) {
+ return AllocStatus::Failed;
+ }
+ return sd_backend_is_cpu(backend) ? AllocStatus::AllocFailed : AllocStatus::DeviceAllocFailed;
+}
+
static int cuda_compiled_arch(ggml_backend_t backend) {
#ifdef SD_USE_CUDA
if (!sd_backend_is(backend, "CUDA")) {
diff --git a/src/core/ggml_runner.cpp b/src/core/ggml_runner.cpp
index b03d662..c6636f2 100644
--- a/src/core/ggml_runner.cpp
+++ b/src/core/ggml_runner.cpp
@@ -165,6 +165,7 @@ bool GGMLRunner::runner_start() {
void GGMLRunner::runner_end() {
GGML_ASSERT(!graph_active_);
execution_engine_->end(execution_session_);
+ token_tile_hint_.reset();
free_compute_ctx();
compute_ctx_buffer_.reset();
}
@@ -262,12 +263,65 @@ void GGMLRunner::cache(const std::string name, ggml_tensor* tensor, ggml_cgraph*
}
}
+std::optional<sd::Tensor<float>> GGMLRunner::compute_with_token_tiles(
+ const std::function<ggml_cgraph*(int64_t)>& build_graph,
+ const std::function<bool(int64_t)>& supports_tile,
+ const std::vector<int64_t>& shape_key,
+ int64_t largest_tile,
+ int64_t smallest_tile,
+ int n_threads) {
+ GGML_ASSERT(smallest_tile > 0 && largest_tile >= smallest_tile);
+ if (!can_segment_graph() || sd_backend_is_cpu(runtime_backend)) {
+ return compute([&] { return build_graph(0); }, n_threads, false);
+ }
+
+ const auto manager = residency_manager.lock();
+ const size_t context_cap = manager ? manager->context_vram_limit(runtime_backend) : 0;
+ const size_t runner_cap = execution_session_.max_backend_bytes();
+ const size_t budget = context_cap && runner_cap ? std::min(context_cap, runner_cap) : std::max(context_cap, runner_cap);
+ const bool cached = token_tile_hint_ && token_tile_hint_->budget == budget && token_tile_hint_->shape_key == shape_key &&
+ (token_tile_hint_->rows == 0 ||
+ (token_tile_hint_->rows >= smallest_tile && token_tile_hint_->rows <= largest_tile &&
+ supports_tile(token_tile_hint_->rows)));
+ int64_t rows = cached ? token_tile_hint_->rows : 0;
+ auto smaller_tile = [&](int64_t current) -> int64_t {
+ if (current == 0) {
+ return largest_tile;
+ }
+ return current > smallest_tile ? std::max(smallest_tile, current / 2) : 0;
+ };
+
+ struct RecoverableScope {
+ bool& flag;
+ const bool saved;
+ ~RecoverableScope() { flag = saved; }
+ } recoverable_scope{capacity_failure_recoverable, capacity_failure_recoverable};
+ for (;;) {
+ int64_t next = smaller_tile(rows);
+ while (next != 0 && !supports_tile(next)) {
+ next = smaller_tile(next);
+ }
+ capacity_failure_recoverable = recoverable_scope.saved || next != 0;
+ auto result = compute([&] { return build_graph(rows); }, n_threads, false);
+ if (last_compute_status_ == GGML_STATUS_SUCCESS) {
+ token_tile_hint_ = TokenTileHint{shape_key, budget, rows};
+ return result;
+ }
+ if (last_compute_failure_ != sd::AllocStatus::DeviceAllocFailed || next == 0) {
+ return result;
+ }
+ LOG_INFO("%s retrying device allocation with %lld tokens per tile", get_desc().c_str(), static_cast<long long>(next));
+ rows = next;
+ }
+}
+
std::optional<sd::Tensor<float>> GGMLRunner::compute(get_graph_cb_t get_graph,
int n_threads,
bool auto_runner_end,
bool no_return,
const std::function<bool()>& read_outputs) {
- last_compute_status_ = GGML_STATUS_FAILED;
+ last_compute_status_ = GGML_STATUS_FAILED;
+ last_compute_failure_ = sd::AllocStatus::Failed;
clear_device_memory_error();
if (graph_active_) {
LOG_ERROR("%s does not support reentrant graph execution", get_desc().c_str());
@@ -321,6 +375,7 @@ std::optional<sd::Tensor<float>> GGMLRunner::compute(get_graph_cb_t get_graph,
auto result = execution_engine_->execute(execution_session_, task);
last_compute_status_ = result.status;
device_memory_error_ = std::move(result.device_memory_error);
+ last_compute_failure_ = result.failure;
success = result.status == GGML_STATUS_SUCCESS;
if (success) {
return std::move(result.output);
diff --git a/src/core/ggml_runner.h b/src/core/ggml_runner.h
index bd94952..2992448 100644
--- a/src/core/ggml_runner.h
+++ b/src/core/ggml_runner.h
@@ -142,6 +142,14 @@ private:
sd::ExecutionSession& execution_session_;
ggml_status last_compute_status_ = GGML_STATUS_SUCCESS;
std::string device_memory_error_;
+ sd::AllocStatus last_compute_failure_ = sd::AllocStatus::Failed;
+
+ struct TokenTileHint {
+ std::vector<int64_t> shape_key;
+ size_t budget = 0;
+ int64_t rows = 0;
+ };
+ std::optional<TokenTileHint> token_tile_hint_;
protected:
typedef std::function<ggml_cgraph*()> get_graph_cb_t;
@@ -234,6 +242,20 @@ protected:
bool prepare_compute_graph(get_graph_cb_t get_graph,
ggml_cgraph** gf_out);
+ bool can_segment_graph() const {
+ return execution_session_.can_segment_graph();
+ }
+
+ // A zero tile size builds the ordinary graph. Builders must be replayable from the
+ // original inputs after a failed allocation, including after earlier cuts ran.
+ std::optional<sd::Tensor<float>> compute_with_token_tiles(
+ const std::function<ggml_cgraph*(int64_t)>& build_graph,
+ const std::function<bool(int64_t)>& supports_tile,
+ const std::vector<int64_t>& shape_key,
+ int64_t largest_tile,
+ int64_t smallest_tile,
+ int n_threads);
+
size_t reusable_compute_buffer_bytes() const {
return execution_session_.compute_bytes();
}
@@ -306,6 +328,7 @@ public:
const std::function<bool()>& read_outputs = {});
ggml_status last_compute_status() const { return last_compute_status_; }
+ bool device_capacity_failure() const { return last_compute_failure_ == sd::AllocStatus::DeviceAllocFailed; }
const std::string& device_memory_error() const { return device_memory_error_; }
void clear_device_memory_error() { device_memory_error_.clear(); }
diff --git a/src/core/runner_cache.cpp b/src/core/runner_cache.cpp
index 9e7078e..48b53b1 100644
--- a/src/core/runner_cache.cpp
+++ b/src/core/runner_cache.cpp
@@ -26,7 +26,8 @@ namespace sd {
ggml_free(context);
}
- std::unique_ptr<CachedTensor> CachedTensor::allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source, bool reuse_only) {
+ std::unique_ptr<CachedTensor> CachedTensor::allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source, AllocStatus& status, bool reuse_only) {
+ status = AllocStatus::AllocFailed;
auto entry = std::make_unique<CachedTensor>();
entry->context = ggml_init({2 * ggml_tensor_overhead(), nullptr, true});
if (entry->context == nullptr) {
@@ -36,11 +37,12 @@ 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());
+ auto buft = ggml_backend_get_default_buffer_type(backend);
+ if (buft == nullptr) {
+ status = AllocStatus::Failed;
+ return nullptr;
+ }
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) {
@@ -51,24 +53,29 @@ namespace sd {
return nullptr;
}
} else {
- entry->buffer = ggml_backend_alloc_ctx_tensors(entry->context, backend);
- }
- if (entry->buffer == nullptr) {
- return nullptr;
+#ifdef SD_USE_UPSTREAM_GGML
+ entry->buffer = ggml_backend_alloc_ctx_tensors_from_buft(entry->context, buft);
+#else
+ entry->buffer = ggml_backend_buft_alloc_buffer_n(buft, &entry->tensor, 1);
+#endif
+ if (entry->buffer == nullptr) {
+ status = backend_alloc_failure(backend);
+ return nullptr;
+ }
}
+ status = AllocStatus::Success;
return entry;
}
std::unique_ptr<CachedTensor> CachedTensor::copy(ggml_backend_t backend,
const std::string& name,
ggml_tensor* source,
- ggml_status& status) {
- status = GGML_STATUS_FAILED;
+ AllocStatus& status) {
+ status = AllocStatus::Failed;
if (ggml_graph_cut::tensor_buffer(source) == nullptr) {
return nullptr;
}
- status = GGML_STATUS_ALLOC_FAILED;
- auto entry = allocate(backend, name, source);
+ auto entry = allocate(backend, name, source, status);
if (entry == nullptr) {
return nullptr;
}
@@ -79,7 +86,6 @@ namespace sd {
} else {
ggml_backend_tensor_copy(source, entry->tensor);
}
- status = GGML_STATUS_SUCCESS;
return entry;
}
@@ -136,9 +142,9 @@ namespace sd {
return pending > SIZE_MAX - committed ? SIZE_MAX : committed + pending;
}
- ggml_status RunnerCache::capture(ggml_cgraph* graph) {
+ AllocStatus RunnerCache::capture(ggml_cgraph* graph) {
if (outputs_.empty()) {
- return GGML_STATUS_SUCCESS;
+ return AllocStatus::Success;
}
const auto tensors = cache_graph_tensors(graph);
for (const auto& output : outputs_) {
@@ -146,7 +152,7 @@ namespace sd {
continue;
}
GGML_ASSERT(ggml_is_contiguous(output.second));
- ggml_status status;
+ AllocStatus status;
auto entry = CachedTensor::copy(backend_, output.first, output.second, status);
if (entry == nullptr) {
return status;
@@ -154,7 +160,7 @@ namespace sd {
pending_[output.first] = std::move(entry);
}
ggml_backend_synchronize(backend_);
- return GGML_STATUS_SUCCESS;
+ return AllocStatus::Success;
}
void RunnerCache::graph_end(bool success) {
@@ -186,7 +192,7 @@ namespace sd {
ggml_is_contiguous(tensor) && ggml_backend_supports_op(backend, tensor);
}
- bool GraphCutTensorCache::bind_outputs(const std::unordered_set<const ggml_tensor*>& outputs, CachedTensors* unused_outputs) {
+ AllocStatus 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);
const auto cached = get(tensor->name);
@@ -207,20 +213,21 @@ namespace sd {
}
}
if (entry == nullptr) {
- entry = CachedTensor::allocate(backend_, tensor->name, tensor, unused_outputs != nullptr);
- }
- if (entry == nullptr) {
- if (unused_outputs != nullptr) {
- continue;
+ AllocStatus status;
+ entry = CachedTensor::allocate(backend_, tensor->name, tensor, status, unused_outputs != nullptr);
+ if (entry == nullptr) {
+ if (unused_outputs != nullptr) {
+ continue;
+ }
+ return status;
}
- return false;
}
tensor->buffer = entry->tensor->buffer;
tensor->data = entry->tensor->data;
tensor->extra = entry->tensor->extra;
tensors_[tensor->name] = std::move(entry);
}
- return true;
+ return AllocStatus::Success;
}
size_t GraphCutTensorCache::estimate_output_bytes(
@@ -262,9 +269,9 @@ namespace sd {
return unused_outputs;
}
- ggml_status GraphCutTensorCache::capture(ggml_cgraph* graph,
- const ggml_graph_cut::Segment& segment,
- const char* log_desc) {
+ AllocStatus GraphCutTensorCache::capture(ggml_cgraph* graph,
+ const ggml_graph_cut::Segment& segment,
+ const char* log_desc) {
size_t copied_bytes = 0;
size_t copied_count = 0;
for (int index : segment.output_node_indices) {
@@ -277,7 +284,7 @@ namespace sd {
if (cached != nullptr && output->buffer == cached->buffer && output->data == cached->data) {
continue;
}
- ggml_status status;
+ AllocStatus status;
auto entry = CachedTensor::copy(backend_, output->name, ggml_graph_cut::cache_source_tensor(output), status);
if (entry == nullptr) {
LOG_ERROR("%s failed to capture graph cut tensor: %s", log_desc, output->name);
@@ -293,6 +300,6 @@ namespace sd {
LOG_DEBUG("%s graph cut cache added %6.2f MB (%zu tensors)",
log_desc, copied_bytes / (1024.f * 1024.f), copied_count);
}
- return GGML_STATUS_SUCCESS;
+ return AllocStatus::Success;
}
}
diff --git a/src/core/runner_cache.h b/src/core/runner_cache.h
index d31a9db..f0888a2 100644
--- a/src/core/runner_cache.h
+++ b/src/core/runner_cache.h
@@ -6,6 +6,7 @@
#include <string>
#include <unordered_set>
+#include "core/alloc_status.h"
#include "ggml-backend.h"
namespace sd::ggml_graph_cut {
@@ -18,11 +19,11 @@ namespace sd {
ggml_backend_buffer_t buffer = nullptr;
ggml_tensor* tensor = nullptr;
~CachedTensor();
- static std::unique_ptr<CachedTensor> allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source, bool reuse_only = false);
+ static std::unique_ptr<CachedTensor> allocate(ggml_backend_t backend, const std::string& name, ggml_tensor* source, AllocStatus& status, bool reuse_only = false);
static std::unique_ptr<CachedTensor> copy(ggml_backend_t backend,
const std::string& name,
ggml_tensor* source,
- ggml_status& status);
+ AllocStatus& status);
};
using CachedTensors = std::map<std::string, std::unique_ptr<CachedTensor>>;
@@ -44,7 +45,7 @@ namespace sd {
size_t pending_bytes(ggml_cgraph* graph) const;
size_t resident_bytes(ggml_backend_dev_t device) const;
bool empty() const { return committed_.empty(); }
- ggml_status capture(ggml_cgraph* graph);
+ AllocStatus capture(ggml_cgraph* graph);
void graph_end(bool success);
void clear();
};
@@ -61,8 +62,8 @@ namespace sd {
size_t estimate_output_bytes(ggml_cgraph* graph,
const ggml_graph_cut::Segment& segment) const;
static bool can_bind_output(ggml_backend_t backend, const ggml_tensor* tensor);
- bool bind_outputs(const std::unordered_set<const ggml_tensor*>& outputs, CachedTensors* unused_outputs = nullptr);
- ggml_status capture(ggml_cgraph* graph, const ggml_graph_cut::Segment& segment, const char* log_desc);
+ AllocStatus bind_outputs(const std::unordered_set<const ggml_tensor*>& outputs, CachedTensors* unused_outputs = nullptr);
+ AllocStatus capture(ggml_cgraph* graph, const ggml_graph_cut::Segment& segment, const char* log_desc);
CachedTensors prune(const std::unordered_set<std::string>& keep_names);
void clear() { tensors_.clear(); }
};
diff --git a/src/core/segment_weight_pipeline.cpp b/src/core/segment_weight_pipeline.cpp
index 0f472db..f0b04c3 100644
--- a/src/core/segment_weight_pipeline.cpp
+++ b/src/core/segment_weight_pipeline.cpp
@@ -71,44 +71,46 @@ namespace sd {
queued_segment_ = SIZE_MAX;
}
- bool SegmentWeightPipeline::ensure_segment_capacity(
+ AllocStatus SegmentWeightPipeline::ensure_segment_capacity(
size_t segment_index,
const std::vector<DeviceMemoryRequest>& requests,
std::string* device_memory_error) {
if (segment_index >= segment_params_.size()) {
- return false;
+ return AllocStatus::Failed;
}
auto manager = residency_manager_.lock();
if (manager == nullptr) {
- return segment_params_[segment_index].empty();
+ return segment_params_[segment_index].empty() ? AllocStatus::Success : AllocStatus::Failed;
}
std::vector<ggml_tensor*> protected_params = segment_params_[segment_index];
protected_params.insert(protected_params.end(), queued_params_.begin(), queued_params_.end());
for (const auto& request : requests) {
- if (!manager->ensure_compute_backend_capacity(request, segment_params_[segment_index],
- preferred_eviction_order(), protected_params, device_memory_error)) {
- return false;
+ const auto status = manager->reserve_compute_backend_capacity(request, segment_params_[segment_index],
+ preferred_eviction_order(), protected_params, device_memory_error);
+ if (status != AllocStatus::Success) {
+ return status;
}
}
- return true;
+ return AllocStatus::Success;
}
- bool SegmentWeightPipeline::segment_start(size_t segment_index, const std::function<bool()>& ensure_capacity) {
+ AllocStatus SegmentWeightPipeline::segment_start(size_t segment_index, const std::function<AllocStatus()>& ensure_capacity) {
GGML_ASSERT(pinned_params_.empty());
const bool prefetched = queued_segment_ == segment_index;
activate(segment_index);
- if (!ensure_capacity()) {
- return false;
+ const auto capacity = ensure_capacity();
+ if (capacity != AllocStatus::Success) {
+ return capacity;
}
auto manager = residency_manager_.lock();
if (manager == nullptr) {
- return segment_params_[segment_index].empty();
+ return segment_params_[segment_index].empty() ? AllocStatus::Success : AllocStatus::Failed;
}
- if (!manager->prepare_params(segment_params_[segment_index], prefetched ? owner_id_ : 0)) {
- return false;
+ const auto status = manager->prepare_params_status(segment_params_[segment_index], prefetched ? owner_id_ : 0);
+ if (status == AllocStatus::Success) {
+ pinned_params_ = segment_params_[segment_index];
}
- pinned_params_ = segment_params_[segment_index];
- return true;
+ return status;
}
void SegmentWeightPipeline::segment_end() {
diff --git a/src/core/segment_weight_pipeline.h b/src/core/segment_weight_pipeline.h
index cbb82e8..7268be0 100644
--- a/src/core/segment_weight_pipeline.h
+++ b/src/core/segment_weight_pipeline.h
@@ -9,6 +9,7 @@
#include <unordered_set>
#include <vector>
+#include "core/alloc_status.h"
#include "ggml-backend.h"
struct DeviceMemoryRequest;
@@ -50,10 +51,10 @@ namespace sd {
~SegmentWeightPipeline();
const std::vector<ggml_tensor*>& params(size_t index) const { return segment_params_[index]; }
- bool ensure_segment_capacity(size_t segment_index,
+ AllocStatus ensure_segment_capacity(size_t segment_index,
const std::vector<DeviceMemoryRequest>& requests,
std::string* device_memory_error);
- bool segment_start(size_t segment_index, const std::function<bool()>& ensure_capacity);
+ AllocStatus segment_start(size_t segment_index, const std::function<AllocStatus()>& ensure_capacity);
void segment_end();
// Prefetch is best effort; segment_start falls back to synchronous loading.
void enqueue_next(size_t segment_index,
diff --git a/src/device_residency_manager.h b/src/device_residency_manager.h
index d61c04d..e6ed9a3 100644
--- a/src/device_residency_manager.h
+++ b/src/device_residency_manager.h
@@ -7,6 +7,7 @@
#include <string>
#include <vector>
+#include "core/alloc_status.h"
#include "ggml-backend.h"
struct ggml_tensor;
@@ -188,7 +189,10 @@ public:
virtual bool assign_compute_backend(const std::vector<ggml_tensor*>& tensors,
ggml_backend_t compute_backend) = 0;
virtual ggml_tensor* resolve_param_tensor(ggml_tensor* tensor) const { return nullptr; }
- virtual bool prepare_params(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) = 0;
+ bool prepare_params(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) {
+ return prepare_params_status(tensors, prefetch_owner) == sd::AllocStatus::Success;
+ }
+ virtual sd::AllocStatus prepare_params_status(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) = 0;
virtual void release_compute_backend_params(const std::vector<ggml_tensor*>& tensors) = 0;
// Drops compute copies of weights whose params location is not the compute device.
virtual void evict_compute_backend_params(const std::vector<ggml_tensor*>& tensors) = 0;
@@ -197,7 +201,16 @@ public:
virtual void update_runtime_residency(uintptr_t owner_id,
ggml_backend_t compute_backend,
size_t resident_bytes) = 0;
- virtual bool ensure_compute_backend_capacity(
+ bool ensure_compute_backend_capacity(
+ const DeviceMemoryRequest& request,
+ const std::vector<ggml_tensor*>& required_params,
+ const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
+ const std::vector<ggml_tensor*>& protected_params,
+ std::string* device_memory_error = nullptr) {
+ return reserve_compute_backend_capacity(request, required_params, preferred_eviction_order, protected_params,
+ device_memory_error) == sd::AllocStatus::Success;
+ }
+ virtual sd::AllocStatus reserve_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
diff --git a/src/model/adapter/lora.hpp b/src/model/adapter/lora.hpp
index 0b6a7ad..9857d74 100644
--- a/src/model/adapter/lora.hpp
+++ b/src/model/adapter/lora.hpp
@@ -1094,8 +1094,7 @@ struct LoraModel : public GGMLRunner {
};
const bool success = GGMLRunner::compute(get_graph, n_threads, false, true, read_outputs).has_value();
if (!success) {
- const bool capacity = !device_memory_error().empty() || last_compute_status() == GGML_STATUS_ALLOC_FAILED;
- if (capacity && capacity_failure_recoverable)
+ if (device_capacity_failure() && capacity_failure_recoverable)
LOG_DEBUG("LoRA graph did not fit in device memory");
else
LOG_ERROR("LoRA graph execution failed");
diff --git a/src/model/adapter/lora_merge.cpp b/src/model/adapter/lora_merge.cpp
index 1e8af58..129a15f 100644
--- a/src/model/adapter/lora_merge.cpp
+++ b/src/model/adapter/lora_merge.cpp
@@ -114,8 +114,7 @@ namespace sd::lora {
next = end;
continue;
}
- capacity_failure = !lora->device_memory_error().empty() ||
- lora->last_compute_status() == GGML_STATUS_ALLOC_FAILED;
+ capacity_failure = lora->device_capacity_failure();
if (capacity_failure && batch.size() == 1) {
progress.capacity_error = lora->device_memory_error().empty() ? "graph allocation failed"
: lora->device_memory_error();
diff --git a/src/model/common/ggml_block.hpp b/src/model/common/ggml_block.hpp
index 203b699..11bffa8 100644
--- a/src/model/common/ggml_block.hpp
+++ b/src/model/common/ggml_block.hpp
@@ -157,14 +157,30 @@ public:
}
ggml_tensor* forward(GGMLRunnerContext* ctx, ggml_tensor* x) override {
+ return forward_rows(ctx, x, 0, out_features);
+ }
+
+ ggml_tensor* forward_rows(GGMLRunnerContext* ctx, ggml_tensor* x, int64_t begin, int64_t end) {
+ GGML_ASSERT(begin >= 0 && begin < end && end <= out_features);
+ const bool sliced = begin != 0 || end != out_features;
+ if (sliced && (ctx->weight_adapter || w4_convrot_kind)) {
+ // Adapter updates and W4 metadata still describe the complete output axis.
+ return ggml_ext_slice(ctx, forward(ctx, x), 0, begin, end, false);
+ }
+ auto select_rows = [&](ggml_tensor* tensor, int axis) {
+ return sliced ? ggml_ext_slice(ctx, tensor, axis, begin, end, false) : tensor;
+ };
const bool force_prec_f32 = ggml_ext_force_prec_f32(ctx, this->force_prec_f32, precision_flags);
- ggml_tensor* w = params["weight"];
+ ggml_tensor* w = select_rows(params["weight"], 1);
const float scale = ctx->linear_scale > 0.f ? ctx->linear_scale : this->scale;
ggml_tensor* weight_scale = has_weight_scale ? params["weight_scale"] : nullptr;
+ if (weight_scale != nullptr && weight_scale->ne[0] == out_features) {
+ weight_scale = select_rows(weight_scale, 0);
+ }
w = ggml_ext_prepare_linear_weight(ctx, w, x, force_prec_f32);
ggml_tensor* b = nullptr;
if (bias) {
- b = params["bias"];
+ b = select_rows(params["bias"], 0);
}
ggml_tensor* linear_bias = has_weight_scale ? nullptr : b;
ggml_tensor* out = nullptr;
diff --git a/src/model/diffusion/minimax_h3.hpp b/src/model/diffusion/minimax_h3.hpp
index b0b5bd7..c4b50f8 100644
--- a/src/model/diffusion/minimax_h3.hpp
+++ b/src/model/diffusion/minimax_h3.hpp
@@ -21,7 +21,10 @@
namespace MiniMaxH3 {
- constexpr int H3_GRAPH_SIZE = 131072;
+ constexpr int H3_GRAPH_SIZE = 131072;
+ // Graph nodes each token tile adds per transformer layer, and the node budget for all tiles.
+ constexpr int64_t H3_TILE_GRAPH_NODES = 80;
+ constexpr int64_t H3_TILE_GRAPH_BUDGET = 3 * H3_GRAPH_SIZE / 2;
constexpr float DEFAULT_ATTN_CHUNK_BUDGET_GIB = 2.f;
constexpr float FRAME_RESCALE = 5.f / 3.f;
constexpr float VISUAL_COND_TIMESTEP = 0.999f;
@@ -286,13 +289,12 @@ namespace MiniMaxH3 {
}
std::vector<ggml_tensor*> chunks;
- for (int64_t start = 0; start < x->ne[1]; start += chunk_size) {
- auto input = ggml_ext_slice(ctx, x, 1, start, std::min(start + chunk_size, x->ne[1]), false);
+ ggml_ext_for_each_token_tile(ctx, x, 0, x->ne[1], chunk_size, false, [&](ggml_tensor* input, int64_t, int64_t) {
if (!ggml_is_contiguous(input)) {
input = ggml_cont(ctx->ggml_ctx, input);
}
chunks.push_back(forward_chunk(input));
- }
+ });
return ggml_ext_vec_concat(ctx, chunks, 1);
}
};
@@ -341,15 +343,15 @@ namespace MiniMaxH3 {
return ggml_concat(ctx->ggml_ctx, ggml_concat(ctx->ggml_ctx, q, k, 0), v, 0);
}
+ ggml_tensor* packed_heads(GGMLRunnerContext* ctx, ggml_tensor* projected, int part) {
+ return ggml_view_4d(ctx->ggml_ctx, projected, head_dim, heads,
+ projected->ne[1], projected->ne[2] * projected->ne[3],
+ head_dim * projected->nb[0], projected->nb[1], projected->nb[2],
+ part * heads * head_dim * projected->nb[0]);
+ }
+
std::vector<ggml_tensor*> split_qkv(GGMLRunnerContext* ctx, ggml_tensor* projected) {
- std::vector<ggml_tensor*> result;
- for (int i = 0; i < 3; ++i) {
- result.push_back(ggml_view_4d(ctx->ggml_ctx, projected, head_dim, heads,
- projected->ne[1], projected->ne[2] * projected->ne[3],
- head_dim * projected->nb[0], projected->nb[1], projected->nb[2],
- i * heads * head_dim * projected->nb[0]));
- }
- return result;
+ return {packed_heads(ctx, projected, 0), packed_heads(ctx, projected, 1), packed_heads(ctx, projected, 2)};
}
std::vector<ggml_tensor*> project_qkv(GGMLRunnerContext* ctx,
@@ -409,6 +411,45 @@ namespace MiniMaxH3 {
return std::dynamic_pointer_cast<UnaryBlock>(blocks["out_proj"])->forward(ctx, x);
}
+ ggml_tensor* project_heads(GGMLRunnerContext* ctx, ggml_tensor* input, const char* name) {
+ auto projected = std::dynamic_pointer_cast<UnaryBlock>(blocks[name])->forward(ctx, input);
+ return ggml_reshape_4d(ctx->ggml_ctx, projected, head_dim, heads, projected->ne[1], input->ne[2]);
+ }
+
+ ggml_tensor* position_projected_heads(GGMLRunnerContext* ctx, ggml_tensor* value, ggml_tensor* pe, int64_t offset, const char* norm_name) {
+ const int64_t tokens = value->ne[2];
+ const int64_t batch = value->ne[3];
+ auto rope = ggml_ext_slice(ctx, pe, 3, offset, offset + tokens, false);
+ auto norm = std::dynamic_pointer_cast<RMSNorm>(blocks[norm_name]);
+ auto positioned = apply_partial_rope(ctx, norm->forward(ctx, value), rope);
+ return ggml_reshape_4d(ctx->ggml_ctx, positioned, head_dim, tokens, heads, batch);
+ }
+
+ GGMLAttentionKV project_kv(GGMLRunnerContext* ctx, ggml_tensor* input, ggml_tensor* pe, int64_t offset) {
+ ggml_tensor* key;
+ ggml_tensor* value;
+ if (split_projections) {
+ key = project_heads(ctx, input, "k_proj");
+ value = project_heads(ctx, input, "v_proj");
+ } else {
+ const int64_t inner = head_dim * heads;
+ auto linear = std::dynamic_pointer_cast<Linear>(blocks["qkv_proj"]);
+ auto kv = linear->forward_rows(ctx, input, inner, 3 * inner);
+ key = packed_heads(ctx, kv, 0);
+ value = packed_heads(ctx, kv, 1);
+ }
+ return {position_projected_heads(ctx, key, pe, offset, "k_norm"), value};
+ }
+
+ ggml_tensor* project_query(GGMLRunnerContext* ctx, ggml_tensor* input, ggml_tensor* pe, int64_t offset) {
+ if (split_projections) {
+ return position_projected_heads(ctx, project_heads(ctx, input, "q_proj"), pe, offset, "q_norm");
+ }
+ auto linear = std::dynamic_pointer_cast<Linear>(blocks["qkv_proj"]);
+ auto query = packed_heads(ctx, linear->forward_rows(ctx, input, 0, head_dim * heads), 0);
+ return position_projected_heads(ctx, query, pe, offset, "q_norm");
+ }
+
ggml_tensor* attend(GGMLRunnerContext* ctx,
const std::vector<ggml_tensor*>& qkv,
ggml_tensor* pe = nullptr) {
@@ -609,7 +650,10 @@ namespace MiniMaxH3 {
ggml_tensor* x,
ggml_tensor* t_emb,
const std::vector<TokenModulationSpan>& segments,
- ggml_tensor* pe) {
+ ggml_tensor* pe,
+ ggml_tensor* token_indices,
+ int64_t tile_rows,
+ const std::string& block_name) {
auto norm1 = std::dynamic_pointer_cast<RMSNorm>(blocks["norm1"]);
auto norm2 = std::dynamic_pointer_cast<RMSNorm>(blocks["norm2"]);
auto attn = std::dynamic_pointer_cast<Attention>(blocks["attn"]);
@@ -627,9 +671,49 @@ namespace MiniMaxH3 {
auto modulate = [&](ggml_tensor* value, const std::vector<ggml_tensor*>& row, int shift, int scale) {
return ggml_ext_modulate(ctx, value, row[shift], row[scale]);
};
- auto qkv = attn->project_qkv(ctx, inputs, [&](ggml_tensor* input, size_t i) {
+ auto prepare_input = [&](ggml_tensor* input, size_t i) {
return modulate(norm1->forward(ctx, input), rows[i], 0, 1);
- });
+ };
+ if (token_indices != nullptr) {
+ GGML_ASSERT(x->ne[2] == 1 && x->ne[3] == 1);
+ // Keeps H3 K/V activations inside FP16 range in the shared K/V buffers.
+ constexpr float tiled_kv_scale = 1.f / 128.f;
+ auto residual = x;
+ ggml_ext_flash_attention_tiled(
+ ctx, inputs, token_indices, attn->head_dim, attn->heads, tile_rows, tiled_kv_scale,
+ [&](const GGMLAttentionTile& tile) {
+ auto input = prepare_input(tile.input, tile.input_index);
+ return attn->project_kv(ctx, input, pe, tile.sequence_offset);
+ },
+ [&](const GGMLAttentionTile& tile) {
+ auto input = prepare_input(tile.input, tile.input_index);
+ return attn->project_query(ctx, input, pe, tile.sequence_offset);
+ },
+ [&](const GGMLAttentionTile& tile, ggml_tensor* attended) {
+ auto projected = attn->project_output(ctx, attended);
+ auto updated = ggml_add(ctx->ggml_ctx, tile.input, ggml_mul(ctx->ggml_ctx, projected, rows[tile.input_index][2]));
+ // Writing x in place relies on single-backend execution in graph order:
+ // K/V are complete, and this tile consumes the last use of these input rows.
+ residual = ggml_set_rows(ctx->ggml_ctx, residual, updated, tile.indices);
+ return residual;
+ });
+ // Keep K/V construction and query tiles together while the input residual is updated in place.
+ const auto attention_group = block_name + ".attn";
+ sd::ggml_graph_cut::mark_graph_cut(mods, attention_group, "mods");
+ sd::ggml_graph_cut::mark_graph_cut(residual, attention_group, "residual");
+
+ std::vector<ggml_tensor*> tiles;
+ for (size_t i = 0; i < segments.size(); ++i) {
+ const auto& segment = segments[i];
+ ggml_ext_for_each_token_tile(ctx, residual, segment.start, segment.end, tile_rows, false, [&](ggml_tensor* input, int64_t, int64_t) {
+ auto h = modulate(norm2->forward(ctx, input), rows[i], 3, 4);
+ tiles.push_back(ggml_add(ctx->ggml_ctx, input, ggml_mul(ctx->ggml_ctx, mlp->forward(ctx, h), rows[i][5])));
+ ctx->expand_graph(tiles.back());
+ });
+ }
+ return ggml_ext_vec_concat(ctx, tiles, 1);
+ }
+ auto qkv = attn->project_qkv(ctx, inputs, prepare_input);
auto attended = attn->attend(ctx, qkv, pe);
std::vector<ggml_tensor*> projections;
for (const auto& segment : segments) {
@@ -856,6 +940,8 @@ namespace MiniMaxH3 {
ggml_tensor* curve_fractions,
const std::vector<TokenModulationSpan>& segments,
const std::vector<SequenceSegment>& sequence_segments,
+ ggml_tensor* token_indices,
+ int64_t tile_rows,
const TokenModulationSpan& video_segment,
const TokenModulationSpan& audio_segment,
float sigma,
@@ -960,11 +1046,11 @@ namespace MiniMaxH3 {
sd::ggml_graph_cut::mark_graph_cut(t_emb, "minimax_h3.prelude", "t_emb");
auto pe = build_rope(ctx, position_ids);
for (int64_t i = 0; i < config.num_layers; ++i) {
- auto block = std::dynamic_pointer_cast<TransformerBlock>(blocks["blocks." + std::to_string(i)]);
- h = block->forward(ctx, h, t_emb, segments, pe);
- sd::ggml_graph_cut::mark_graph_cut(h,
- "minimax_h3.blocks." + std::to_string(i),
- "hidden_states");
+ const auto name = "blocks." + std::to_string(i);
+ auto block = std::dynamic_pointer_cast<TransformerBlock>(blocks[name]);
+ const auto cut = "minimax_h3." + name;
+ h = block->forward(ctx, h, t_emb, segments, pe, token_indices, tile_rows, cut);
+ sd::ggml_graph_cut::mark_graph_cut(h, cut, "hidden_states");
}
auto final_layer = std::dynamic_pointer_cast<FinalLayer>(blocks["final_layer"]);
@@ -1257,6 +1343,7 @@ namespace MiniMaxH3 {
sd::Tensor<int32_t> curve_index_input_cache;
sd::Tensor<int32_t> curve_upper_index_input_cache;
sd::Tensor<float> curve_fraction_input_cache;
+ sd::Tensor<int32_t> token_index_input_cache;
MiniMaxH3Runner(ggml_backend_t backend,
const String2TensorStorage& tensors,
@@ -1316,17 +1403,16 @@ namespace MiniMaxH3 {
}
ggml_cgraph* build_graph(const sd::Tensor<float>& packed,
- const sd::Tensor<float>& timestep,
const sd::Tensor<float>& context_tensor,
const std::vector<sd::Tensor<float>>& condition_videos,
const std::vector<sd::Tensor<float>>& condition_audios,
- const sd::Tensor<int32_t>& text_tags,
- const sd::Tensor<int32_t>& keyframe_indices,
- const std::vector<MiniMaxH3ReferenceBlock>& reference_blocks,
+ const PackedSequenceLayout& layout,
int audio_length,
- float video_shift,
- float audio_shift,
- float video_sigma_next) {
+ float sigma_v,
+ float sigma_a,
+ float audio_scale,
+ float video_sigma_next,
+ int64_t tile_rows) {
GGML_ASSERT(packed.dim() == 4 || packed.dim() == 5);
GGML_ASSERT(audio_length > 0 || config.audio_latent_channels == 0);
GGML_ASSERT(!context_tensor.empty());
@@ -1362,40 +1448,10 @@ namespace MiniMaxH3 {
audio_condition_inputs.push_back(make_input(condition));
}
- float sigma_v = std::clamp(timestep[0] / 1000.f, 1e-6f, 1.f);
- float sigma_a = time_shift_sigma(sigma_v, video_shift, audio_shift);
- float audio_scale = video_shift / audio_shift;
- float t_v = 1.f - sigma_v;
- float t_a = 1.f - sigma_a;
- float r_v = t_v;
- float r_a = t_a;
- if (config.two_time) {
- if (std::isfinite(video_sigma_next)) {
- float next = std::clamp(video_sigma_next, 0.f, 1.f);
- r_v = 1.f - next;
- r_a = 1.f - time_shift_sigma(next, video_shift, audio_shift);
- } else {
- LOG_WARN("two-time checkpoint without a step endpoint; using r = t");
- }
- }
// The sampler carries c_a = (sigma_v / sigma_a) * x_a so the packed
// latent follows one sigma schedule. Restore x_a for the H3 network.
auto audio_ctx = get_context();
auto audio = audio_carrier == nullptr ? nullptr : ggml_ext_scale(&audio_ctx, audio_carrier, sigma_a / sigma_v);
- auto layout = build_layout(context_tensor.shape()[1],
- packed.shape()[2],
- packed.shape()[1],
- packed.shape()[0],
- audio_length,
- condition_videos,
- condition_audios,
- keyframe_indices,
- reference_blocks,
- text_tags,
- t_v,
- t_a,
- r_v,
- r_a);
position_input_cache = sd::Tensor<float>(
{3, static_cast<int64_t>(layout.positions.size() / 3)},
@@ -1452,7 +1508,25 @@ namespace MiniMaxH3 {
}
}
- auto graph = new_graph_custom(H3_GRAPH_SIZE);
+ ggml_tensor* token_indices = nullptr;
+ size_t graph_size = H3_GRAPH_SIZE;
+ if (tile_rows != 0) {
+ int64_t tiles = 0;
+ for (const auto& segment : layout.segments) {
+ tiles += (segment.end - segment.start + tile_rows - 1) / tile_rows;
+ }
+ graph_size += static_cast<size_t>(tiles * H3_TILE_GRAPH_NODES * config.num_layers);
+ const int64_t tokens = static_cast<int64_t>(layout.positions.size() / 3);
+ if (token_index_input_cache.empty() || token_index_input_cache.numel() != tokens) {
+ std::vector<int32_t> indices(tokens);
+ for (int64_t i = 0; i < tokens; ++i) {
+ indices[i] = static_cast<int32_t>(i);
+ }
+ token_index_input_cache = sd::Tensor<int32_t>({tokens}, std::move(indices));
+ }
+ token_indices = make_input(token_index_input_cache);
+ }
+ auto graph = new_graph_custom(graph_size);
auto runner_ctx = get_context(graph);
auto output = model.forward(&runner_ctx,
video,
@@ -1468,6 +1542,8 @@ namespace MiniMaxH3 {
curve_fractions,
layout.segments,
layout.sequence_segments,
+ token_indices,
+ tile_rows,
layout.video_segment,
layout.audio_segment,
sigma_v,
@@ -1499,23 +1575,103 @@ namespace MiniMaxH3 {
? empty_reference_blocks
: *extra->reference_blocks;
const sd::Tensor<int32_t> empty_int;
- auto get_graph = [&]() {
- return build_graph(*params.x,
- *params.timesteps,
- *params.context,
- conditions,
- audio_conditions,
- extra->text_token_tags == nullptr ? empty_int : *extra->text_token_tags,
- extra->keyframe_indices == nullptr ? empty_int : *extra->keyframe_indices,
- reference_blocks,
- extra->audio_length,
- extra->video_sigma_shift,
- extra->audio_sigma_shift,
- extra->video_sigma_next);
+ float sigma_v = std::clamp((*params.timesteps)[0] / 1000.f, 1e-6f, 1.f);
+ float sigma_a = time_shift_sigma(sigma_v, extra->video_sigma_shift, extra->audio_sigma_shift);
+ float audio_scale = extra->video_sigma_shift / extra->audio_sigma_shift;
+ float t_v = 1.f - sigma_v;
+ float t_a = 1.f - sigma_a;
+ float r_v = t_v;
+ float r_a = t_a;
+ if (config.two_time) {
+ if (std::isfinite(extra->video_sigma_next)) {
+ float next = std::clamp(extra->video_sigma_next, 0.f, 1.f);
+ r_v = 1.f - next;
+ r_a = 1.f - time_shift_sigma(next, extra->video_sigma_shift, extra->audio_sigma_shift);
+ } else {
+ LOG_WARN("two-time checkpoint without a step endpoint; using r = t");
+ }
+ }
+ auto layout = build_layout(params.context->shape()[1],
+ params.x->shape()[2],
+ params.x->shape()[1],
+ params.x->shape()[0],
+ extra->audio_length,
+ conditions,
+ audio_conditions,
+ extra->keyframe_indices == nullptr ? empty_int : *extra->keyframe_indices,
+ reference_blocks,
+ extra->text_token_tags == nullptr ? empty_int : *extra->text_token_tags,
+ t_v,
+ t_a,
+ r_v,
+ r_a);
+
+ auto get_graph = [&](int64_t tile_rows) {
+ return build_graph(*params.x, *params.context, conditions, audio_conditions, layout,
+ extra->audio_length, sigma_v, sigma_a, audio_scale, extra->video_sigma_next, tile_rows);
+ };
+ const auto whole_graph = [&] {
+ return restore_trailing_singleton_dims(GGMLRunner::compute([&] { return get_graph(0); }, n_threads, false),
+ params.x->dim());
+ };
+ if (!can_segment_graph() || !flash_attn_enabled || sage_attn_enabled) {
+ return whole_graph();
+ }
+
+ // Bound the tiled graph metadata as well as the device workspace. Each span can
+ // contribute a partial tile independently, and all layers are built before execution.
+ const int64_t max_tiles = H3_TILE_GRAPH_BUDGET / (H3_TILE_GRAPH_NODES * config.num_layers);
+ const int64_t full_tiles = max_tiles - static_cast<int64_t>(layout.segments.size());
+ if (full_tiles <= 0) {
+ return whole_graph();
+ }
+ const int64_t tokens = static_cast<int64_t>(layout.positions.size() / 3);
+ constexpr int64_t tile_alignment = 256;
+ const int64_t min_rows = ((tokens - 1) / (full_tiles * tile_alignment) + 1) * tile_alignment;
+ const int64_t max_rows = std::max<int64_t>(4096, min_rows);
+ if (tokens <= min_rows) {
+ return whole_graph();
+ }
+
+ // Span boundaries come from the input sequence layout. Only modulation row indices vary with timestep.
+ std::vector<int64_t> shape_key{tokens};
+ for (const auto& segment : layout.segments) {
+ shape_key.insert(shape_key.end(), {segment.start, segment.end});
+ }
+ auto supports_tile = [&](int64_t rows) {
+ std::vector<int64_t> lengths;
+ lengths.reserve(layout.segments.size() + 1);
+ for (const auto& segment : layout.segments) {
+ const int64_t span = segment.end - segment.start;
+ if (span >= rows) {
+ lengths.push_back(rows);
+ }
+ if (span % rows != 0) {
+ lengths.push_back(span % rows);
+ }
+ }
+ std::sort(lengths.begin(), lengths.end());
+ lengths.erase(std::unique(lengths.begin(), lengths.end()), lengths.end());
+ // build_graph unpacks one video and one audio stream into a single sequence.
+ constexpr int64_t batch = 1;
+ if (!ggml_ext_supports_tiled_flash_attention(runtime_backend, config.attention_head_dim,
+ config.num_attention_heads, tokens, batch, lengths)) {
+ return false;
+ }
+ const std::unique_ptr<ggml_context, decltype(&ggml_free)> probe(
+ ggml_init({(1 + 3 * lengths.size()) * ggml_tensor_overhead(), nullptr, true}), ggml_free);
+ if (!probe) {
+ return false;
+ }
+ auto c = probe.get();
+ auto residual = ggml_new_tensor_3d(c, GGML_TYPE_F32, config.hidden_size, tokens, batch);
+ return std::all_of(lengths.begin(), lengths.end(), [&](int64_t length) {
+ auto update = ggml_new_tensor_3d(c, GGML_TYPE_F32, config.hidden_size, length, batch);
+ auto indices = ggml_new_tensor_1d(c, GGML_TYPE_I32, length);
+ return ggml_backend_supports_op(runtime_backend, ggml_set_rows(c, residual, update, indices));
+ });
};
- return restore_trailing_singleton_dims(GGMLRunner::compute(get_graph,
- n_threads,
- false),
+ return restore_trailing_singleton_dims(compute_with_token_tiles(get_graph, supports_tile, shape_key, max_rows, min_rows, n_threads),
params.x->dim());
}
};
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index a485543..c06f3c4 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -984,7 +984,7 @@ ggml_backend_t ModelManager::next_residency_backend(const TensorState& state, gg
return nullptr;
}
-bool ModelManager::ensure_device_capacity(const DeviceMemoryRequest& request,
+sd::AllocStatus ModelManager::reserve_device_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,
@@ -1074,8 +1074,9 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
// prepare_params() loads released weights of this request again after staging.
DeviceMemoryRequest request{compute_backend, 0, bytes};
request.reloadable_params = &protected_params;
- if (!ensure_device_capacity(request, {}, {}, protected_params)) {
- capacity_failure = true;
+ const auto status = reserve_device_capacity(request, {}, {}, protected_params);
+ if (status != sd::AllocStatus::Success) {
+ capacity_failure = status == sd::AllocStatus::DeviceAllocFailed;
return false;
}
}
@@ -1604,8 +1605,9 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
for (const auto& [device, limit] : devices) {
DeviceMemoryRequest request{device, 0, chunk_size, 0, limit, reused_bytes};
request.recoverable = capacity_failure != nullptr;
- if (device && !ensure_device_capacity(request, {}, {}, protected_params)) {
- if (capacity_failure) {
+ const auto status = device ? reserve_device_capacity(request, {}, {}, protected_params) : sd::AllocStatus::Success;
+ if (status != sd::AllocStatus::Success) {
+ if (capacity_failure && status == sd::AllocStatus::DeviceAllocFailed) {
*capacity_failure = true;
LOG_INFO("model manager cannot fit params buffer on %s", ggml_backend_name(device));
} else {
@@ -2250,7 +2252,7 @@ bool ModelManager::fits_compute_backend_capacity(
: check_capacity(request, states, check).fits();
}
-bool ModelManager::ensure_compute_backend_capacity(
+sd::AllocStatus ModelManager::reserve_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
@@ -2259,7 +2261,7 @@ bool ModelManager::ensure_compute_backend_capacity(
{
std::vector<TensorState*> states;
if (!resolve_required_tensor_states(required_params, states, request.compute_backend))
- return false;
+ return sd::AllocStatus::Failed;
if (request.compute_backend && !sd_backend_is_cpu(request.compute_backend))
place_first_loads(request, states);
const auto devices = split_devices_for(states);
@@ -2276,10 +2278,12 @@ bool ModelManager::ensure_compute_backend_capacity(
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;
+ const auto status = reserve_device_capacity(peer, {}, preferred_eviction_order, protected_weights, device_memory_error);
+ if (status != sd::AllocStatus::Success) {
+ return status;
+ }
}
}
}
- return ensure_device_capacity(request, required_params, preferred_eviction_order, protected_params, device_memory_error);
+ return reserve_device_capacity(request, required_params, preferred_eviction_order, protected_params, device_memory_error);
}
diff --git a/src/model_manager.h b/src/model_manager.h
index 145668a..7de9d8e 100644
--- a/src/model_manager.h
+++ b/src/model_manager.h
@@ -229,7 +229,7 @@ private:
bool prefers_compute_residency(const TensorState& state) const;
bool demote_params_storage_block(ParamsStorageBlock* block, const std::vector<TensorState*>& protected_states);
bool copy_params_storage_block(ParamsStorageBlock& block, ggml_backend_t target, const std::vector<TensorState*>& protected_states);
- bool ensure_device_capacity(const DeviceMemoryRequest& request,
+ sd::AllocStatus reserve_device_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,
@@ -237,8 +237,7 @@ private:
// Steps of prepare_params().
bool ready_for_compute(const TensorState& state) const;
// Loads and stages the weights so the compute device can read them.
- // capacity_failure reports that staging ran out of device memory.
- bool ensure_copies(const std::vector<TensorState*>& states, bool* capacity_failure = nullptr, uintptr_t prefetch_owner = 0);
+ sd::AllocStatus ensure_copies(const std::vector<TensorState*>& states, uintptr_t prefetch_owner = 0);
void release_unprepared(const std::vector<TensorState*>& states);
// Returns the use epoch; 0 starts a new one.
uint64_t lease_states(const std::vector<TensorState*>& states, uint64_t use_epoch = 0);
@@ -263,7 +262,7 @@ private:
// Merges the pending LoRA versions of a request's weights; reports whether device memory stopped it, and why.
using MergeFn = std::function<bool(const std::vector<TensorState*>&, bool& capacity_failure, std::string& capacity_error)>;
// Merges the request's pending LoRA versions a batch of targets at a time, then loads every copy.
- bool merge_in_batches(const std::vector<TensorState*>& states, const MergeFn& merge);
+ sd::AllocStatus merge_in_batches(const std::vector<TensorState*>& states, const MergeFn& merge);
// A weight that should hold the current LoRA version but does not.
const TensorState* unmerged_weight(const std::vector<TensorState*>& states) const;
bool mmap_params(const std::vector<TensorState*>& states,
@@ -443,7 +442,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;
+ sd::AllocStatus prepare_params_status(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, bool require_available = false) override;
void register_runtime_owner(uintptr_t owner_id) override;
void remove_runtime_owner(uintptr_t owner_id) override;
@@ -459,7 +458,7 @@ public:
void update_runtime_residency(uintptr_t owner_id,
ggml_backend_t compute_backend,
size_t resident_bytes) override;
- bool ensure_compute_backend_capacity(
+ sd::AllocStatus reserve_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
@@ -575,8 +574,8 @@ public:
return manager_->assign_compute_backend(tensors, backend);
}
ggml_tensor* resolve_param_tensor(ggml_tensor* tensor) const override { return manager_->resolve_param_tensor(tensor); }
- bool prepare_params(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) override {
- return manager_->prepare_params(tensors, prefetch_owner);
+ sd::AllocStatus prepare_params_status(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner = 0) override {
+ return manager_->prepare_params_status(tensors, prefetch_owner);
}
void release_compute_backend_params(const std::vector<ggml_tensor*>& tensors) override {
manager_->release_compute_backend_params(tensors);
@@ -593,12 +592,12 @@ public:
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,
+ sd::AllocStatus reserve_compute_backend_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required,
const std::vector<std::vector<ggml_tensor*>>& preferred,
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error) override {
- return manager_->ensure_compute_backend_capacity(request, required, preferred, protected_params, device_memory_error);
+ return manager_->reserve_compute_backend_capacity(request, required, preferred, protected_params, device_memory_error);
}
DeviceMemoryCapacity inspect_compute_backend_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& params,
diff --git a/src/model_manager_prepare.cpp b/src/model_manager_prepare.cpp
index bd35b00..a2ea55b 100644
--- a/src/model_manager_prepare.cpp
+++ b/src/model_manager_prepare.cpp
@@ -15,20 +15,20 @@
// copies and commits them. Allocation, reading, leases, merges and rollback share one lifecycle,
// so the flow and its intermediate state stay inside ModelManager.
-bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner) {
+sd::AllocStatus ModelManager::prepare_params_status(const std::vector<ggml_tensor*>& tensors, uintptr_t prefetch_owner) {
if (tensors.empty())
- return true;
+ return sd::AllocStatus::Success;
std::vector<TensorState*> states;
if (!resolve_required_tensor_states(tensors, states))
- return false;
+ return sd::AllocStatus::Failed;
for (const auto* state : states) {
if (state != nullptr && state->sources.empty()) {
LOG_ERROR("required tensor '%s' is missing from model metadata", state->name.c_str());
- return false;
+ return sd::AllocStatus::Failed;
}
}
if (states.empty())
- return true;
+ return sd::AllocStatus::Success;
std::map<ggml_backend_t, std::vector<TensorState*>> by_compute;
for (auto* state : states) {
@@ -77,12 +77,12 @@ bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors, uint
// Readable copies of every weight. Merged copies are as large as their originals, so when
// these do not fit, merging in batches would not fit at the end either.
- const bool copies_ready = ensure_copies(states, nullptr, prefetch_owner);
+ const auto copies = ensure_copies(states, prefetch_owner);
if (prefetch_owner)
clear_prefetched_params(prefetch_owner);
- if (!copies_ready) {
+ if (copies != sd::AllocStatus::Success) {
release_unprepared(states);
- return false;
+ return copies;
}
// Merge pending LoRA versions, then commit them on the copies written. The merge leases the
@@ -129,7 +129,13 @@ bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors, uint
} restore{*this, yielding, use_epoch};
capacity_failure = false;
capacity_error.clear();
- merged = merge(states, capacity_failure, capacity_error) && ensure_copies(states);
+ merged = merge(states, capacity_failure, capacity_error);
+ if (merged) {
+ const auto restored = ensure_copies(states);
+ if (restored != sd::AllocStatus::Success) {
+ return restored;
+ }
+ }
}
}
if (!merged && capacity_failure) {
@@ -142,8 +148,9 @@ bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors, uint
merge_progress.clear();
return merge(batch, failed, error);
};
- if (!merge_in_batches(states, merge_fresh))
- return false;
+ const auto status = merge_in_batches(states, merge_fresh);
+ if (status != sd::AllocStatus::Success)
+ return status;
lease_states(states, use_epoch);
leases.held = true;
if (const auto* missing = unmerged_weight(states)) {
@@ -151,17 +158,17 @@ bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors, uint
"immediate LoRA lost the merged copy of '%s': not enough RAM to keep merged weights off the device "
"(raise --max-ram or use --lora-apply-mode at_runtime)",
missing->name.c_str());
- return false;
+ return sd::AllocStatus::Failed;
}
} else if (!merged) {
- return false;
+ return sd::AllocStatus::Failed;
}
leases.held = false;
check_residency();
- return true;
+ return sd::AllocStatus::Success;
}
-bool ModelManager::merge_in_batches(const std::vector<TensorState*>& states, const MergeFn& merge) {
+sd::AllocStatus ModelManager::merge_in_batches(const std::vector<TensorState*>& states, const MergeFn& merge) {
// Only the batch being merged is leased, so the merge reclaims every other weight of the
// request; merged copies leave the device through the merged RAM cache and stage again from it.
const auto units = pending_merges(states);
@@ -202,12 +209,13 @@ bool ModelManager::merge_in_batches(const std::vector<TensorState*>& states, con
}
// Stages, leases and merges one batch. Either step may run out of device memory; a failed
// batch drops what it wrote.
- auto merge_batch = [&](const std::vector<TensorState*>& batch, bool& capacity_failure, std::string& capacity_error) {
- if (!ensure_copies(batch, &capacity_failure)) {
+ auto merge_batch = [&](const std::vector<TensorState*>& batch, std::string& capacity_error) {
+ const auto copies = ensure_copies(batch);
+ if (copies != sd::AllocStatus::Success) {
release_unprepared(batch);
- if (capacity_failure)
+ if (copies == sd::AllocStatus::DeviceAllocFailed)
capacity_error = "staging the batch's weights does not fit in device memory";
- return false;
+ return copies;
}
lease_states(batch);
struct BatchLeases {
@@ -220,8 +228,12 @@ bool ModelManager::merge_in_batches(const std::vector<TensorState*>& states, con
manager.abandon_merge(batch);
}
} leases{*this, batch};
+ bool capacity_failure = false;
leases.merged = merge(batch, capacity_failure, capacity_error);
- return leases.merged;
+ if (leases.merged) {
+ return sd::AllocStatus::Success;
+ }
+ return capacity_failure ? sd::AllocStatus::DeviceAllocFailed : sd::AllocStatus::Failed;
};
LOG_INFO("merging immediate LoRA in batches to fit device memory (%zu targets)", units.size());
while (!batches.empty()) {
@@ -234,15 +246,15 @@ bool ModelManager::merge_in_batches(const std::vector<TensorState*>& states, con
if (units[index].scale)
batch.push_back(units[index].scale);
}
- bool capacity_failure = false;
std::string capacity_error;
- if (merge_batch(batch, capacity_failure, capacity_error))
+ const auto status = merge_batch(batch, capacity_error);
+ if (status == sd::AllocStatus::Success)
continue;
- if (!capacity_failure)
- return false;
+ if (status != sd::AllocStatus::DeviceAllocFailed)
+ return status;
if (end - first == 1) {
LOG_ERROR("immediate LoRA does not fit in device memory: %s", capacity_error.c_str());
- return false;
+ return status;
}
const size_t middle = first + (end - first) / 2;
batches.emplace_front(middle, end);
@@ -311,19 +323,17 @@ bool ModelManager::ready_for_compute(const TensorState& state) const {
(state.param_source() == ParamSource::Backend && state.compute_backend == state.params_backend()));
}
-bool ModelManager::ensure_copies(const std::vector<TensorState*>& states, bool* capacity_failure, uintptr_t prefetch_owner) {
+sd::AllocStatus ModelManager::ensure_copies(const std::vector<TensorState*>& states, uintptr_t prefetch_owner) {
// Reclaims made for these weights may release some of them (reload bytes in the plan), so
// loading repeats until a pass leaves every weight in place.
for (int pass = 0; pass < 3; ++pass) {
bool load_capacity = false, staging_capacity = false;
- if (!load_tensors_to_params_backend(states, capacity_failure ? &load_capacity : nullptr, prefetch_owner) ||
+ if (!load_tensors_to_params_backend(states, &load_capacity, prefetch_owner) ||
!stage_tensors_to_compute_backend(states, staging_capacity, prefetch_owner) || !ensure_host_capacity(0, states)) {
- if (capacity_failure)
- *capacity_failure = load_capacity || staging_capacity;
- return false;
+ return load_capacity || staging_capacity ? sd::AllocStatus::DeviceAllocFailed : sd::AllocStatus::Failed;
}
if (std::all_of(states.begin(), states.end(), [&](const TensorState* state) { return ready_for_compute(*state); }))
- return true;
+ return sd::AllocStatus::Success;
}
for (const auto* state : states) {
if (!ready_for_compute(*state)) {
@@ -332,7 +342,7 @@ bool ModelManager::ensure_copies(const std::vector<TensorState*>& states, bool*
break;
}
}
- return false;
+ return sd::AllocStatus::Failed;
}
void ModelManager::release_unprepared(const std::vector<TensorState*>& states) {
diff --git a/src/model_manager_reclaim.cpp b/src/model_manager_reclaim.cpp
index 6ee843f..cec3d14 100644
--- a/src/model_manager_reclaim.cpp
+++ b/src/model_manager_reclaim.cpp
@@ -271,7 +271,7 @@ bool ModelManager::copy_params_storage_block(ParamsStorageBlock& block,
DeviceMemoryRequest request{target, 0, bytes};
request.quiet = true;
request.release_only = true;
- fits = ensure_device_capacity(request, {}, {}, protected_params);
+ fits = reserve_device_capacity(request, {}, {}, protected_params) == sd::AllocStatus::Success;
}
if (!fits) {
return false;
diff --git a/src/weights/capacity.h b/src/weights/capacity.h
index 05dc70f..4a951a2 100644
--- a/src/weights/capacity.h
+++ b/src/weights/capacity.h
@@ -14,7 +14,7 @@ namespace sd::weights {
public:
virtual ~CapacityProvider() = default;
// required: weights the allocation is for; protected_params stay through the reclaim.
- virtual bool reserve(const DeviceMemoryRequest& request,
+ virtual AllocStatus reserve(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,