feat: run CPU graphs in segments when weights stream from disk

Without a GPU, auto-fit now compares the available RAM with the size of
each component and leaves the ones that do not fit on disk. When it does,
it turns the memory guard on at 90% unless --memory-guard is set.

On CPU backends the memory guard now counts the weights a graph still has
to read from disk before they are loaded. When that total would pass the
threshold and some weights can be released, the graph runs in segments, as
it already does on a GPU, so the peak stays well below the size of the
model. Splitting is skipped when the guard is off or when every weight is
resident, because it could not lower the peak.

Checked with a synthetic SD 1.5 model (128x128, 3 steps, 2 threads, Linux):
with 3.3 GiB of RAM held by another process and a 60% guard, the UNet runs
in 22 segments with a 732 MiB peak instead of 1722 MiB and the image is
identical pixel for pixel. Resident weights and runs without pressure or
without the guard behave as before. Not tested on Windows or with real
models.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
This commit is contained in:
Claude 2026-10-11 06:39:34 +02:00
parent 7ed90dace3
commit 0d84e104ee
No known key found for this signature in database
12 changed files with 159 additions and 13 deletions

View file

@ -210,6 +210,17 @@ weight to be copied again at every step.
RAM and GPU budgets are shared across components. Each component uses a single
parameter backend; several other GPUs' capacities are not combined to store
one component. If available RAM cannot be queried, RAM residency is skipped.
Without a GPU (a CPU-only machine, or every GPU backend unavailable) the same
planning runs against the CPU: the diffusion model, text encoder and VAE are
considered in the usual order, and each one stays in RAM if its weights fit in
what is left of the available RAM after the 2 GiB / 10% margin and the largest
compute reserve (computation also needs RAM). A component that does not fit
reads its weights from disk, and auto-fit then turns the memory guard on at 90%
(unless `--memory-guard` is set) so that the graph runs in segments and weights
are released between them. When everything fits, the plan changes nothing and
the log says `auto-fit: CPU only; the weights fit in RAM`. If available RAM
cannot be queried, the default backend and placement are used.
Weights stored on another GPU are copied to the component's compute devices for
execution. CPU modules use RAM or disk. Compute reserves and cache priority are
accounted for separately on each device, so a CPU module does not reserve GPU

View file

@ -327,6 +327,7 @@ Che cosa è automatico e che cosa no:
| Windows impedisce l'avvio dell'eseguibile (EACCES/EPERM) | policy di sicurezza, es. Smart App Control, o binario bloccato | controllare Sicurezza di Windows e i registri CodeIntegrity; usare binari attendibili; **non** disattivare le protezioni |
| Generazione lentissima (minuti per passo) | esecuzione sulla CPU, risoluzione alta, o modello troppo grande per la memoria | verificare i device; ridurre risoluzione/passi; modello quantizzato; build GPU |
| Avviso "memory guard: pressure" nei log | la memoria del device (su CPU: la RAM di sistema) ha superato la soglia `--memory-guard` | è un avviso con riduzione automatica della residenza: evitare nuove richieste finché non segnala il recupero |
| `auto-fit: CPU only; ...` nei log | senza GPU il motore ha confrontato la RAM disponibile con le dimensioni dei componenti | `the weights fit in RAM`: nessuna azione. `some weights do not fit in RAM; enabling the memory guard at 90%`: i componenti che non ci stanno restano su disco e il grafo gira a segmenti; è più lento ma serve proprio a non esaurire la RAM |
### 2.9 Pacchetto portabile (consigliato per la distribuzione)
```shell
@ -661,6 +662,16 @@ dei pacchetti portabili automatici descritti sopra.
continua. La percentuale riguarda l'intera macchina, non solo questo
processo, e sulle piattaforme che non riportano la memoria disponibile il
guardiano su CPU non fa nulla.
I pesi che vengono letti dal disco contano prima di essere caricati: se il
totale supererebbe la soglia, il grafo su CPU viene eseguito a segmenti
(come su GPU) e il picco di memoria resta ben sotto il modello intero. Succede
solo se esistono pesi rilasciabili (`--params-backend disk`); con tutti i
pesi in RAM il grafo resta intero, perché spezzarlo non abbasserebbe il
picco. Senza GPU, `--auto-fit` pianifica la RAM contro la CPU e, se mette un
componente su disco, imposta la soglia a 90 (salvo `--memory-guard`
esplicito). Su Linux la memoria disponibile viene da `/proc/meminfo`, che
non rispecchia il limite di memoria di un container: lì conviene passare a
mano `--memory-guard` e `--params-backend disk`.
Gli avvisi di pressione alta/critica e di recupero sono accessibili tramite
il callback di log; l'applicazione ospite può mostrarli senza interrompere
la generazione. Un eventuale monitor RAM nell'applicazione resta un controllo
@ -889,6 +900,22 @@ sincronizzazioni future.
sostituire o cancellare il file del modello mentre il motore lo usa
(come già accadeva con `--mmap`). Test: `test/file_handle_pool_test.cpp`
(ASan/UBSan e ThreadSanitizer).
14. **CPU senza GPU: auto-fit e grafi a segmenti** — senza GPU, `--auto-fit`
confronta la RAM disponibile con i componenti (pesi e riserva di
calcolo) e lascia su disco quelli che non ci stanno; in quel caso attiva da
solo la memory guard al 90% (salvo `--memory-guard` esplicito). Sui backend
CPU la guardia conta i pesi ancora da leggere dal disco prima di caricarli
e, se il totale supererebbe la soglia, il grafo gira a segmenti (come su
GPU) invece che intero; avviene solo se esistono pesi rilasciabili
(`--params-backend disk`), perché con tutti i pesi in RAM spezzare il grafo
non abbasserebbe il picco (`ModelManager::segmenting_can_save_memory`,
`src/core/backend_fit.cpp`). Misure con un modello SD 1.5 sintetico
(128×128, 3 passi, 2 thread, Linux, 3,3 GiB occupati da un altro processo,
soglia 60%): UNet in 22 segmenti, picco 732 MiB invece di 1722 MiB, 23 s
invece di 12 s, immagine identica pixel per pixel; con pesi residenti in
RAM e la stessa pressione nessuna segmentazione (come prima); senza
pressione il comportamento non cambia. Non ancora provato su Windows né
con modelli reali.
Passaggi previsti e non ancora svolti: collaudo del workflow di release sui
runner GitHub, generazione con un modello reale (inclusa la memory guard sotto

View file

@ -186,6 +186,22 @@ continues. RAM is shared with other programs, so the percentage covers the whole
machine, not only this process. The guard never fails a graph on the CPU, and it
does nothing on platforms that cannot report available memory.
Weights that stream from disk are counted before they are loaded, so on the CPU
the guard sees what a graph is about to need and not only what is resident. When
that total would pass the threshold, a graph that has graph cuts runs in segments,
as it does on a GPU: each segment reads its weights, computes, and lets them go
before the next one starts, which keeps the peak well below the whole model. This
only applies when some weights can be released (`--params-backend disk`); if
every weight is resident in RAM, splitting the graph would not lower the peak and
the graph runs in one piece. `--disable-segmented-compute` turns segmentation off.
On a machine without a GPU, `--auto-fit` plans RAM against the CPU backend (see
[backend.md](./backend.md#automatic-placement---auto-fit-onoff)) and, when it
puts a component on disk, sets the guard to 90 unless `--memory-guard` is given.
On Linux, available memory comes from `/proc/meminfo`, which does not reflect the
limit of a container's memory cgroup; inside a container with such a limit, pass
`--memory-guard` and `--params-backend disk` explicitly and leave headroom.
## Use quantization to reduce memory usage.
[quantization](./quantization_and_gguf.md)

View file

@ -595,7 +595,9 @@ ArgOptions SDContextParams::get_options() {
&conditioning_cache_size},
{"",
"--memory-guard",
"memory usage percent (device memory, or system RAM on CPU backends) that triggers pressure reduction (weight eviction, prefetch pause) before allocations fail, e.g. 90 (default: 0, disabled)",
"memory usage percent (device memory, or system RAM on CPU backends) that triggers pressure reduction (weight eviction, prefetch pause) before allocations fail, e.g. 90 (default: 0, disabled). "
"On CPU backends, weights still to be read from disk count before they are loaded, and the graph runs in segments when they would not fit. "
"With no GPU, --auto-fit enables it at 90 when some weights do not fit in RAM",
&memory_guard},
};
@ -749,6 +751,7 @@ ArgOptions SDContextParams::get_options() {
"--auto-fit",
"on|off (default: on). Preserve --backend (otherwise select one GPU) and place weights on the compute GPU, "
"RAM, another GPU, or disk in that order, according to available memory (--max-vram limits GPU budgets). "
"With no GPU, each component stays in RAM if it fits in the available RAM and is read from disk otherwise. "
"Disabled by explicit --params-backend; uses automatic graph segmentation when needed",
[this](int argc, const char** argv, int index) {
return parse_on_off_arg(argc, argv, index, "--auto-fit", auto_fit);

View file

@ -251,7 +251,7 @@ typedef struct {
const char* tokenizer; // tokenizer.json path or main=FILE,clip-l=FILE,clip-g=FILE assignments; required for PiD and Lens
bool sage_attn;
int conditioning_cache_size; // Maximum cached conditioning entries per context; 0 disables caching (default: 4)
int memory_guard; // Memory usage percent (device memory, or system RAM on CPU backends) that triggers pressure reduction (weight eviction, prefetch pause); 0 disables (default)
int memory_guard; // Memory usage percent (device memory, or system RAM on CPU backends) that triggers pressure reduction (weight eviction, prefetch pause, segmented CPU graphs for weights read from disk); 0 disables (default). Auto-fit uses 90 for a CPU-only plan that reads weights from disk
bool disable_backend_fallback; // Fail context creation instead of falling back to the CPU backend when the requested backend is unavailable
} sd_ctx_params_t;

View file

@ -419,7 +419,8 @@ namespace sd::backend_fit {
ggml_type override_wtype,
sd::ggml_graph_cut::MaxVramAssignment& budgets,
std::string& runtime_spec,
std::string& params_spec) {
std::string& params_spec,
int& memory_guard_percent) {
std::string error;
if (!budgets.canonicalize_backend_keys(&error)) {
LOG_ERROR("%s", error.c_str());
@ -435,8 +436,25 @@ namespace sd::backend_fit {
LOG_ERROR("%s", error.c_str());
return false;
}
const int64_t free_ram = available_ram_bytes();
const int64_t ram_budget = std::max<int64_t>(free_ram - std::max<int64_t>(2048 * MiB, free_ram / 10), 0);
const int64_t free_ram = available_ram_bytes();
// Without a GPU everything runs on the CPU and the compute buffers come out of RAM too.
const bool cpu_only = devices.empty() && std::all_of(runtimes.begin(), runtimes.end(), [](const Runtime& runtime) {
return runtime.devices.empty();
});
if (cpu_only && runtimes.empty()) {
if (free_ram < 0) {
LOG_WARN("auto-fit: no GPU devices and available RAM is unknown; using the default backend");
return true;
}
runtimes.assign(components.size(), Runtime{"CPU", {}});
}
int64_t compute_reserve = 0;
if (cpu_only) {
for (const Component& comp : components) {
compute_reserve = std::max(compute_reserve, comp.reserve_bytes);
}
}
const int64_t ram_budget = std::max<int64_t>(free_ram - std::max<int64_t>(2048 * MiB, free_ram / 10) - compute_reserve, 0);
const auto plan = compute_plan(components, devices, ram_budget, runtimes);
params_spec.clear();
if (!plan.valid) {
@ -450,6 +468,19 @@ namespace sd::backend_fit {
}
print_plan(plan, components, devices, free_ram, ram_budget);
if (cpu_only) {
const bool streams_from_disk = std::any_of(plan.decisions.begin(), plan.decisions.end(), [](const Decision& decision) {
return decision.params_location == ParamsLocation::DISK;
});
if (!streams_from_disk) {
LOG_INFO("auto-fit: CPU only; the weights fit in RAM");
return true;
}
if (memory_guard_percent <= 0) {
memory_guard_percent = 90;
LOG_INFO("auto-fit: CPU only and some weights do not fit in RAM; enabling the memory guard at %d%% so the model runs in segments", memory_guard_percent);
}
}
for (size_t ci = 0; ci < components.size(); ++ci) {
if (components[ci].params_bytes == 0) {
continue;

View file

@ -10,11 +10,14 @@
namespace sd::backend_fit {
// memory_guard_percent is raised from 0 when the plan runs a component on the CPU with its
// weights read from disk: without the guard nothing would release them between segments.
bool derive_backend_specs(ModelLoader& loader,
ggml_type override_wtype,
sd::ggml_graph_cut::MaxVramAssignment& budgets,
std::string& runtime_spec,
std::string& params_spec);
std::string& params_spec,
int& memory_guard_percent);
bool prepare_vae_decode_retry_tiling(sd_tiling_params_t& tiling_params,
bool prefer_temporal_tiling,

View file

@ -847,8 +847,9 @@ std::optional<Tensor<float>> GGMLRunner::execute_graph(ggml_cgraph* graph, int n
return fits(requests, params);
};
auto manager = residency_manager.lock();
const bool segmented = !is_multi_device() && !sd_backend_is_cpu(runtime_backend) &&
const bool segmented = !is_multi_device() &&
manager != nullptr && manager->segmented_compute_enabled() &&
(!sd_backend_is_cpu(runtime_backend) || manager->segmenting_can_save_memory(params, runtime_backend)) &&
cached_plan.valid && cached_plan.has_cuts && cached_plan.segments.size() > 1 &&
!fits_monolithic();
ggml_graph_cut::Plan monolithic_plan;

View file

@ -46,6 +46,10 @@ struct DeviceResidencyManager {
// Capacity requests select their backend's weights; protection spans all backends.
virtual bool fits_compute_backend_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params) const = 0;
// False when splitting a graph into segments cannot lower peak memory on a host backend:
// no memory guard is set, or every weight stays resident once loaded.
virtual bool segmenting_can_save_memory(const std::vector<ggml_tensor*>& params,
ggml_backend_t compute_backend) const { return true; }
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; }

View file

@ -1863,12 +1863,52 @@ bool ModelManager::memory_guard_ok(const DeviceMemoryRequest& request) const {
sd::MemoryWatchdog::Pressure::None;
}
// Weights read from disk into host memory become resident in system RAM, but the guard only
// sees RAM that is already in use. Counting the weights this graph still has to load lets it
// tell before loading whether the whole graph fits or has to run in segments.
DeviceMemoryRequest ModelManager::with_streamed_weights(DeviceMemoryRequest request,
const std::vector<TensorState*>& states) const {
std::vector<TensorState*> streamed;
for (TensorState* state : states) {
if (state != nullptr && state->residency_mode == ResidencyMode::Disk) {
streamed.push_back(state);
}
}
const size_t missing = compute_backend_alloc_size(streamed, true);
request.pending_allocation_bytes = missing > SIZE_MAX - request.pending_allocation_bytes
? SIZE_MAX
: request.pending_allocation_bytes + missing;
return request;
}
bool ModelManager::segmenting_can_save_memory(const std::vector<ggml_tensor*>& params,
ggml_backend_t compute_backend) const {
if (compute_backend == nullptr || !sd_backend_is_cpu(compute_backend)) {
return true;
}
if (!memory_watchdog_.enabled()) {
return false;
}
std::vector<TensorState*> states;
if (!resolve_required_tensor_states(params, states, compute_backend)) {
return false;
}
return std::any_of(states.begin(), states.end(), [](const TensorState* state) {
return state != nullptr && state->residency_mode == ResidencyMode::Disk;
});
}
bool ModelManager::fits_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params) const {
std::vector<TensorState*> states;
return resolve_required_tensor_states(required_params, states, request.compute_backend) &&
check_capacity(request, states).fits() && memory_guard_ok(request);
if (!resolve_required_tensor_states(required_params, states, request.compute_backend)) {
return false;
}
if (request.compute_backend != nullptr && sd_backend_is_cpu(request.compute_backend)) {
return memory_guard_ok(with_streamed_weights(request, states));
}
return check_capacity(request, states).fits() && memory_guard_ok(request);
}
bool ModelManager::ensure_compute_backend_capacity(
@ -1891,10 +1931,11 @@ bool ModelManager::ensure_compute_backend_capacity(
return true;
}
memory_watchdog_.observe(compute_backend, memory_guard_sample(request), !host_backend);
const DeviceMemoryRequest guard_request = host_backend ? with_streamed_weights(request, required_states) : request;
memory_watchdog_.observe(compute_backend, memory_guard_sample(guard_request), !host_backend);
// System RAM has no managed capacity on the CPU: only the memory guard applies there.
auto fits = [&]() { return host_backend || check_capacity(request, required_states).fits(); };
auto satisfied = [&]() { return fits() && memory_guard_ok(request); };
auto satisfied = [&]() { return fits() && memory_guard_ok(guard_request); };
if (satisfied()) {
return true;
}
@ -1977,7 +2018,7 @@ bool ModelManager::ensure_compute_backend_capacity(
if (!fits()) {
return false;
}
memory_watchdog_.observe(compute_backend, memory_guard_sample(request), !host_backend);
memory_watchdog_.observe(compute_backend, memory_guard_sample(guard_request), !host_backend);
if (memory_watchdog_.should_log_unreachable(compute_backend)) {
LOG_WARN("memory guard: cannot reduce %s below %d%% usage, continuing under pressure",
ggml_backend_name(compute_backend), memory_watchdog_.threshold_percent());

View file

@ -165,6 +165,8 @@ private:
sd::MemoryWatchdog::Sample memory_guard_sample(const DeviceMemoryRequest& request) const;
bool memory_guard_ok(const DeviceMemoryRequest& request) const;
DeviceMemoryRequest with_streamed_weights(DeviceMemoryRequest request,
const std::vector<TensorState*>& states) const;
ggml_backend_buffer_type_t params_buffer_type_for(const TensorState& state) const;
ggml_backend_buffer_type_t split_buffer_type_for(const TensorState& state) const;
@ -281,6 +283,8 @@ public:
bool fits_compute_backend_capacity(const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params) const override;
bool segmented_compute_enabled() const override { return !segmented_compute_disabled_; }
bool segmenting_can_save_memory(const std::vector<ggml_tensor*>& params,
ggml_backend_t compute_backend) const override;
bool prefetch_enabled() const override {
return !prefetch_disabled_ && !memory_watchdog_.prefetch_suspended();
}

View file

@ -1017,13 +1017,18 @@ bool StableDiffusionGGML::init(const sd_ctx_params_t* sd_ctx_params) {
}
if (auto_fit_enabled) {
int memory_guard_percent = sd_ctx_params->memory_guard;
if (!sd::backend_fit::derive_backend_specs(model_loader,
sd_type_to_ggml_type(sd_ctx_params->wtype),
max_vram_assignment,
backend_spec,
params_backend_spec)) {
params_backend_spec,
memory_guard_percent)) {
return false;
}
if (memory_guard_percent != sd_ctx_params->memory_guard) {
model_manager->set_memory_guard_percent(memory_guard_percent);
}
}
if (!init_backend()) {