From edf17ca2f47ee5e70bc40abe4d80bd75f8e9fb2d Mon Sep 17 00:00:00 2001 From: Koreprobro <31925346+Koreprobro@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:43:09 +0300 Subject: [PATCH 1/2] fix: release weight staging of executed segments under layer split MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Layer-split sessions could not use segmented execution, and device-side weight staging copies of already-executed segments were only released on the make_enough_memory() failure path — by which time the previous segment is still pinned, so the allocator, not the estimator, took the hit. Secondary devices accumulated every block they executed (+394 MB per Q8_0 block measured) and died mid-run with cudaMalloc OOM. - admit layer-split sessions to segmented execution; - right after segment_start() releases the previous segment's pins, evict its staging copies before this segment allocates its workspace; - make graph cut caches device-aware: allocate cut outputs on the producing node's device (device-matched reuse of pruned buffers), give cross-device consumers maintained local copies, and count cache residency per backend so capacity checks see secondary devices. Partially addresses #2371. --- src/core/execution_engine.cpp | 43 ++++++++++++---- src/core/runner_cache.cpp | 79 ++++++++++++++++++++++++++--- src/core/runner_cache.h | 19 +++++-- src/core/segment_graph_bindings.cpp | 6 ++- src/core/segment_graph_bindings.h | 4 +- 5 files changed, 127 insertions(+), 24 deletions(-) diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp index c04d4d218..c35c8ff24 100644 --- a/src/core/execution_engine.cpp +++ b/src/core/execution_engine.cpp @@ -554,7 +554,8 @@ 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_) && + const bool can_segment = (!is_multi_device() || session_.layer_split_enabled_) && + !sd_backend_is_cpu(session_.backend_) && session_.segmented_compute_ && cached_plan.valid && cached_plan.has_cuts && cached_plan.segments.size() > 1; // An empty workspace request is a lower bound on the full graph's memory demand. @@ -608,6 +609,16 @@ namespace sd { plan.segments.size(), plan.segments.size() == 1 ? "" : "s"); } SegmentGraphBindings bindings(session_.cut_cache_, plan, graph); + auto backend_for_tensor = [&](const ggml_tensor* tensor) -> ggml_backend_t { + auto it = session_.node_assignments_.find(tensor); + return it == session_.node_assignments_.end() ? session_.backend_ : it->second; + }; + auto segment_backend = [&](const ggml_graph_cut::Segment& seg) -> ggml_backend_t { + if (!session_.node_assignments_.empty() && !seg.internal_node_indices.empty()) { + return backend_for_tensor(ggml_graph_node(graph, seg.internal_node_indices.front())); + } + return session_.backend_; + }; SegmentWeightPipeline weights(manager, session_.backend_, session_.owner_id(), graph, plan, params_tensor_set_, segmented && session_.prefetch_enabled_); @@ -636,7 +647,7 @@ namespace sd { }; auto unused_cut_outputs = session_.cut_cache_.prune(segment.live_cut_names); bindings.reset(segment); - if (!bindings.bind_cached_inputs(segment, task_.description.c_str())) { + if (!bindings.bind_cached_inputs(segment, task_.description.c_str(), segmented ? segment_backend(segment) : nullptr)) { return fail_segment("input binding"); } ggml_context* segment_context = nullptr; @@ -664,13 +675,14 @@ namespace sd { for (int output_index : segment.output_node_indices) { auto tensor = ggml_graph_node(graph, output_index); if (ggml_graph_cut::is_graph_cut_tensor(tensor) && segment.future_cut_names.count(tensor->name) && - GraphCutTensorCache::can_bind_output(session_.backend_, tensor)) { + GraphCutTensorCache::can_bind_output(segmented ? backend_for_tensor(tensor) : session_.backend_, tensor)) { cache_outputs.insert(tensor); } } } // Transfer storage from consumed cuts before releasing it to the bounded pool. - session_.cut_cache_.bind_outputs(cache_outputs, &unused_cut_outputs); + session_.cut_cache_.bind_outputs(cache_outputs, &unused_cut_outputs, + segmented ? backend_for_tensor : GraphCutTensorCache::BackendResolver{}); unused_cut_outputs.clear(); auto measurement = segmented ? measure(segment_graph, &cache_outputs) : full_measurement; if (!session_.workspace_.prepare(measurement)) { @@ -711,6 +723,12 @@ namespace sd { if (!weights.segment_start(index, ensure_capacity)) { return fail_segment("weight preparation"); } + if (segmented && index > 0 && manager != nullptr) { + // segment_start released the previous segment's weight pins; now its device + // staging copies are free to drop before this segment allocates its workspace. + // Prefetched staging for later segments is pinned out of eviction by the pipeline. + manager->evict_compute_backend_params(weights.params(index - 1)); + } // Preparing weights can execute LoRA graphs and reclaim an idle workspace. if (!session_.workspace_.prepare(measurement)) { last_compute_status_ = GGML_STATUS_ALLOC_FAILED; @@ -719,7 +737,8 @@ namespace sd { if (!ensure_capacity()) { return fail_segment("workspace capacity check"); } - if (!session_.cut_cache_.bind_outputs(cache_outputs)) { + if (!session_.cut_cache_.bind_outputs(cache_outputs, nullptr, + segmented ? backend_for_tensor : GraphCutTensorCache::BackendResolver{})) { last_compute_status_ = GGML_STATUS_ALLOC_FAILED; return fail_segment("output cache allocation"); } @@ -764,7 +783,8 @@ namespace sd { } auto cache_status = session_.cache_.capture(segment_graph); if (cache_status == GGML_STATUS_SUCCESS) { - cache_status = session_.cut_cache_.capture(graph, segment, task_.description.c_str()); + cache_status = session_.cut_cache_.capture(graph, segment, task_.description.c_str(), + segmented ? backend_for_tensor : GraphCutTensorCache::BackendResolver{}); } if (cache_status != GGML_STATUS_SUCCESS) { last_compute_status_ = cache_status; @@ -817,11 +837,12 @@ namespace sd { size_t ExecutionSession::resident_bytes(ggml_backend_t backend) const { size_t bytes = workspace_.bytes(backend); - if (backend == backend_) { - const auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; }; - bytes = add(bytes, cache_.resident_bytes(ggml_backend_get_device(backend))); - bytes = add(bytes, cut_cache_.resident_bytes(ggml_backend_get_device(backend))); - } + const auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; }; + // Cut and runner caches track their own buffer devices; count them per backend so + // layer-split residency on secondary devices is visible to capacity checks. + const auto dev = ggml_backend_get_device(backend); + bytes = add(bytes, cache_.resident_bytes(dev)); + bytes = add(bytes, cut_cache_.resident_bytes(dev)); return bytes; } diff --git a/src/core/runner_cache.cpp b/src/core/runner_cache.cpp index 9e7078e08..8f0e90641 100644 --- a/src/core/runner_cache.cpp +++ b/src/core/runner_cache.cpp @@ -177,8 +177,53 @@ namespace sd { return cached_tensor(tensors_, name); } + ggml_tensor* GraphCutTensorCache::local_copy(ggml_backend_t consumer, const std::string& name, ggml_tensor* source) { + auto& per_backend = local_copies_[consumer]; + auto found = per_backend.find(name); + if (found != per_backend.end()) { + return found->second->tensor; + } + ggml_status status; + auto entry = CachedTensor::copy(consumer, name, source, status); + if (entry == nullptr || status != GGML_STATUS_SUCCESS) { + LOG_ERROR("graph cut cache failed to copy tensor to consumer backend: %s", name.c_str()); + per_backend.erase(name); + return nullptr; + } + ggml_tensor* result = entry->tensor; + per_backend[name] = std::move(entry); + return result; + } + + ggml_tensor* GraphCutTensorCache::get_local(ggml_backend_t consumer, const std::string& name) { + ggml_tensor* tensor = get(name); + if (tensor == nullptr || consumer == nullptr) { + return tensor; + } + ggml_backend_buffer_t buffer = ggml_graph_cut::tensor_buffer(tensor); + if (buffer == nullptr) { + return tensor; + } + ggml_backend_dev_t source_device = ggml_backend_buft_get_device(ggml_backend_buffer_get_type(buffer)); + ggml_backend_dev_t consumer_device = ggml_backend_get_device(consumer); + if (source_device == nullptr || source_device == consumer_device) { + return tensor; + } + return local_copy(consumer, name, tensor); + } + + void GraphCutTensorCache::invalidate_local_copies(const std::string& name) { + for (auto& per_backend : local_copies_) { + per_backend.second.erase(name); + } + } + size_t GraphCutTensorCache::resident_bytes(ggml_backend_dev_t device) const { - return sd::resident_bytes(tensors_, device); + size_t bytes = sd::resident_bytes(tensors_, device); + for (const auto& per_backend : local_copies_) { + bytes += sd::resident_bytes(per_backend.second, device); + } + return bytes; } bool GraphCutTensorCache::can_bind_output(ggml_backend_t backend, const ggml_tensor* tensor) { @@ -186,19 +231,27 @@ namespace sd { ggml_is_contiguous(tensor) && ggml_backend_supports_op(backend, tensor); } - bool GraphCutTensorCache::bind_outputs(const std::unordered_set& outputs, CachedTensors* unused_outputs) { + bool GraphCutTensorCache::bind_outputs(const std::unordered_set& outputs, + CachedTensors* unused_outputs, + const BackendResolver& backend_for_output) { for (const ggml_tensor* output : outputs) { auto tensor = const_cast(output); const auto cached = get(tensor->name); if (cached != nullptr && tensor->buffer == cached->buffer && tensor->data == cached->data) { continue; } + ggml_backend_t target = backend_for_output ? backend_for_output(tensor) : nullptr; + if (target == nullptr) { + target = backend_; + } std::unique_ptr entry; if (unused_outputs != nullptr) { - auto match = std::find_if(unused_outputs->begin(), unused_outputs->end(), [&](const auto& item) { + const auto target_device = ggml_backend_get_device(target); + auto match = std::find_if(unused_outputs->begin(), unused_outputs->end(), [&](const auto& item) { const auto* previous = item.second->tensor; return tensor->type == previous->type && ggml_are_same_shape(tensor, previous) && - std::equal(std::begin(tensor->nb), std::end(tensor->nb), std::begin(previous->nb)); + std::equal(std::begin(tensor->nb), std::end(tensor->nb), std::begin(previous->nb)) && + ggml_backend_buft_get_device(ggml_backend_buffer_get_type(item.second->buffer)) == target_device; }); if (match != unused_outputs->end()) { entry = std::move(match->second); @@ -207,7 +260,7 @@ namespace sd { } } if (entry == nullptr) { - entry = CachedTensor::allocate(backend_, tensor->name, tensor, unused_outputs != nullptr); + entry = CachedTensor::allocate(target, tensor->name, tensor, unused_outputs != nullptr); } if (entry == nullptr) { if (unused_outputs != nullptr) { @@ -218,6 +271,7 @@ namespace sd { tensor->buffer = entry->tensor->buffer; tensor->data = entry->tensor->data; tensor->extra = entry->tensor->extra; + invalidate_local_copies(tensor->name); tensors_[tensor->name] = std::move(entry); } return true; @@ -259,12 +313,18 @@ namespace sd { unused_outputs.insert(tensors_.extract(current)); } } + for (auto& per_backend : local_copies_) { + for (auto it = per_backend.second.begin(); it != per_backend.second.end();) { + it = keep_names.count(it->first) ? std::next(it) : per_backend.second.erase(it); + } + } return unused_outputs; } ggml_status GraphCutTensorCache::capture(ggml_cgraph* graph, const ggml_graph_cut::Segment& segment, - const char* log_desc) { + const char* log_desc, + const BackendResolver& backend_for_output) { size_t copied_bytes = 0; size_t copied_count = 0; for (int index : segment.output_node_indices) { @@ -277,8 +337,12 @@ namespace sd { if (cached != nullptr && output->buffer == cached->buffer && output->data == cached->data) { continue; } + ggml_backend_t target = backend_for_output ? backend_for_output(output) : nullptr; + if (target == nullptr) { + target = backend_; + } ggml_status status; - auto entry = CachedTensor::copy(backend_, output->name, ggml_graph_cut::cache_source_tensor(output), status); + auto entry = CachedTensor::copy(target, 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); return status; @@ -286,6 +350,7 @@ namespace sd { const size_t size = ggml_backend_buffer_get_size(entry->buffer); copied_bytes = size > SIZE_MAX - copied_bytes ? SIZE_MAX : copied_bytes + size; ++copied_count; + invalidate_local_copies(output->name); tensors_[output->name] = std::move(entry); } ggml_backend_synchronize(backend_); diff --git a/src/core/runner_cache.h b/src/core/runner_cache.h index d31a9db27..799f7304f 100644 --- a/src/core/runner_cache.h +++ b/src/core/runner_cache.h @@ -1,6 +1,7 @@ #ifndef __SD_CORE_RUNNER_CACHE_H__ #define __SD_CORE_RUNNER_CACHE_H__ +#include #include #include #include @@ -52,19 +53,31 @@ namespace sd { class GraphCutTensorCache { ggml_backend_t backend_; CachedTensors tensors_; + // Consumer-side local copies for cross-device cut consumption (layer split). + std::map local_copies_; + ggml_tensor* local_copy(ggml_backend_t consumer, const std::string& name, ggml_tensor* source); + void invalidate_local_copies(const std::string& name); public: + using BackendResolver = std::function; + explicit GraphCutTensorCache(ggml_backend_t backend) : backend_(backend) {} ggml_tensor* get(const std::string& name) const; + // Cached tensor usable by a consumer on `consumer`: the shared entry when it already + // lives on that device, otherwise a maintained local copy on the consumer's device. + ggml_tensor* get_local(ggml_backend_t consumer, const std::string& name); size_t resident_bytes(ggml_backend_dev_t device) const; 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& outputs, CachedTensors* unused_outputs = nullptr); - ggml_status capture(ggml_cgraph* graph, const ggml_graph_cut::Segment& segment, const char* log_desc); + bool bind_outputs(const std::unordered_set& outputs, + CachedTensors* unused_outputs = nullptr, + const BackendResolver& backend_for_output = nullptr); + ggml_status capture(ggml_cgraph* graph, const ggml_graph_cut::Segment& segment, const char* log_desc, + const BackendResolver& backend_for_output = nullptr); CachedTensors prune(const std::unordered_set& keep_names); - void clear() { tensors_.clear(); } + void clear() { tensors_.clear(); local_copies_.clear(); } }; } diff --git a/src/core/segment_graph_bindings.cpp b/src/core/segment_graph_bindings.cpp index 72a773abd..1480e0096 100644 --- a/src/core/segment_graph_bindings.cpp +++ b/src/core/segment_graph_bindings.cpp @@ -7,6 +7,7 @@ #include "core/runner_cache.h" #include "core/util.h" #include "ggml.h" +#include "ggml-backend.h" namespace sd { SegmentGraphBindings::SegmentGraphBindings(GraphCutTensorCache& tensor_cache, @@ -103,7 +104,8 @@ namespace sd { bool SegmentGraphBindings::bind_cached_inputs( const ggml_graph_cut::Segment& segment, - const char* log_desc) { + const char* log_desc, + ggml_backend_t consumer_backend) { std::unordered_map cached_view_sources; for (const auto& input : segment.input_refs) { if (input.type != ggml_graph_cut::Segment::INPUT_PREVIOUS_CUT) { @@ -113,7 +115,7 @@ namespace sd { if (input_tensor == nullptr) { continue; } - ggml_tensor* cached_tensor = tensor_cache_.get(input.display_name); + ggml_tensor* cached_tensor = tensor_cache_.get_local(consumer_backend, input.display_name); if (cached_tensor == nullptr) { LOG_ERROR("%s missing graph cut cache tensor: %s", log_desc, diff --git a/src/core/segment_graph_bindings.h b/src/core/segment_graph_bindings.h index 6e3e4129c..83a5af9e7 100644 --- a/src/core/segment_graph_bindings.h +++ b/src/core/segment_graph_bindings.h @@ -4,6 +4,7 @@ #include #include #include +#include "ggml-backend.h" #include "ggml.h" struct ggml_backend_buffer; @@ -28,7 +29,8 @@ namespace sd { void restore(); ~SegmentGraphBindings() { restore(); } bool bind_cached_inputs(const ggml_graph_cut::Segment& segment, - const char* log_desc); + const char* log_desc, + ggml_backend_t consumer_backend = nullptr); private: struct ExternalBinding { From 9982c121f495665e939db6b6c2e0c3038dc630a9 Mon Sep 17 00:00:00 2001 From: Koreprobro <31925346+Koreprobro@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:43:09 +0300 Subject: [PATCH 2/2] feat: add MiniMax-H3 projection chunk budget model arg ggml_backend_buft_get_max_size() is unbounded on CUDA, so token chunking of FeedForward::forward() and Attention::project_qkv() was a no-op there: long-sequence canvases allocated multi-GB monolithic projection outputs (6.8 GB qkv buffer + 6.9 GB concat at HD 264f). 'minimax_h3_mlp_chunk_budget_gib=' (--model-args) caps the shared block-level token-chunk budget; default 0 keeps current behavior. Partially addresses #2371. --- src/model/diffusion/minimax_h3.hpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/model/diffusion/minimax_h3.hpp b/src/model/diffusion/minimax_h3.hpp index bd26d82d7..ac446c413 100644 --- a/src/model/diffusion/minimax_h3.hpp +++ b/src/model/diffusion/minimax_h3.hpp @@ -23,6 +23,12 @@ namespace MiniMaxH3 { constexpr int H3_GRAPH_SIZE = 131072; constexpr float DEFAULT_ATTN_CHUNK_BUDGET_GIB = 2.f; + // Optional token-chunk budget for the MiniMax-H3 MLP projections (GiB; 0 disables extra chunking). + // Set via --model-args minimax_h3_mlp_chunk_budget_gib=. Process-wide by design: one model per process. + static inline float& h3_mlp_chunk_budget_gib() { + static float value = 0.f; + return value; + } constexpr float FRAME_RESCALE = 5.f / 3.f; constexpr float VISUAL_COND_TIMESTEP = 0.999f; @@ -276,6 +282,11 @@ namespace MiniMaxH3 { size_t alignment = ggml_backend_buft_get_alignment(buft); size_t chunk_budget = ggml_backend_buft_get_max_size(buft); chunk_budget -= chunk_budget % alignment; + if (h3_mlp_chunk_budget_gib() > 0.f) { + size_t cap = static_cast(h3_mlp_chunk_budget_gib() * (1024.f * 1024.f * 1024.f)); + cap -= cap % alignment; + chunk_budget = std::min(chunk_budget, cap); + } // Use the backend's preferred allocation size as a conservative chunk budget. // Matmul outputs are F32 even for quantized weights. size_t token_bytes = ggml_row_size(GGML_TYPE_F32, std::max(x->ne[0], 2 * ffn_hidden_size)) * x->ne[2] * x->ne[3]; @@ -366,6 +377,11 @@ namespace MiniMaxH3 { // This is a conservative chunk budget, not an operation support limit. size_t chunk_budget = ggml_backend_buft_get_max_size(buft); chunk_budget -= chunk_budget % alignment; + if (h3_mlp_chunk_budget_gib() > 0.f) { + size_t cap = static_cast(h3_mlp_chunk_budget_gib() * (1024.f * 1024.f * 1024.f)); + cap -= cap % alignment; + chunk_budget = std::min(chunk_budget, cap); + } size_t token_bytes = ggml_row_size(GGML_TYPE_F32, 3 * heads * head_dim) * inputs[0]->ne[2] * inputs[0]->ne[3]; chunk_size = static_cast(std::min(chunk_size, std::max(1, chunk_budget / token_bytes))); } @@ -1271,6 +1287,14 @@ namespace MiniMaxH3 { } else { LOG_WARN("ignoring invalid MiniMax-H3 model arg '%s=%s': expected a finite non-negative GiB budget", key.c_str(), value.c_str()); } + } else if (key == "minimax_h3_mlp_chunk_budget_gib") { + float parsed = 0.f; + if (parse_strict_float(value, parsed) && std::isfinite(parsed) && parsed >= 0.f) { + h3_mlp_chunk_budget_gib() = parsed; + LOG_INFO("MiniMax-H3 MLP chunk budget: %.3g GiB (0 disables token chunking)", parsed); + } else { + LOG_WARN("ignoring invalid MiniMax-H3 model arg '%s=%s': expected a finite non-negative GiB budget", key.c_str(), value.c_str()); + } } } std::vector blocks;