Commit 7c293e1 for stable-diffusion.cpp
commit 7c293e11cc28e8d9ff735c522e7598417e943fbc
Author: leejet <leejet714@gmail.com>
Date: Mon Nov 30 23:02:42 2026 +0800
feat: manage weight residency across GPU, RAM, and disk (#2470)
diff --git a/AGENTS.md b/AGENTS.md
index 9be6f7c..89d2eb7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -60,6 +60,8 @@ Current source layout includes:
serialization helpers.
* `src/runtime/` - sampling, denoising, guidance, caching, preprocessing, and
runtime execution helpers.
+* `src/weights/` - weight residency state and reclaim decisions. See the
+ [weight residency internals](docs/development/weights.md).
* `src/tokenizers/` - tokenizer implementations.
* `src/conditioning/` - conditioning and prompt-related implementation.
* `src/extensions/` - optional feature extensions.
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 550cc3d..67b6f63 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -291,6 +291,8 @@ file(GLOB SD_LIB_SOURCES CONFIGURE_DEPENDS
"src/tokenizers/*.cpp"
"src/tokenizers/vocab/*.h"
"src/tokenizers/vocab/*.cpp"
+ "src/weights/*.h"
+ "src/weights/*.cpp"
)
find_program(GIT_EXE NAMES git git.exe NO_CMAKE_FIND_ROOT_PATH)
diff --git a/docs/README.md b/docs/README.md
index a421455..891db91 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -43,6 +43,7 @@ For the project overview and supported models, see the [project README](../READM
- [C API internals](development/c_api.md)
- [DGL architecture](development/dgl.md)
+- [Weight residency internals](development/weights.md)
- [Model configuration and integration conventions](development/model_config.md)
- [ggml operator extensions](development/ggml_extensions.md)
- [Backend performance probes](development/backend_probe.md)
diff --git a/docs/development/weights.md b/docs/development/weights.md
new file mode 100644
index 0000000..24851c6
--- /dev/null
+++ b/docs/development/weights.md
@@ -0,0 +1,227 @@
+# Weight residency internals
+
+`src/weights/` holds weight residency logic that does not depend on runner or
+graph code. It currently contains the residency snapshot and the reclaim
+planner. `ModelManager` (`src/model_manager*.cpp`) still owns the allocations
+and executes the planned actions; it is expected to move into this directory
+later. For user-facing behavior, see
+[weight residency](../guides/backend.md#weight-residency).
+
+## Responsibilities
+
+| Responsibility | Owner |
+| --- | --- |
+| Component placement: compute devices and params backend | `dgl/run_plan` (auto-fit) |
+| Weight state: copies, shared aliases, leases, LoRA epochs, adapter weights | `ModelManager` |
+| Reclaim decisions | `weights/reclaim_planner` (pure) |
+| Reading weights from model files and mapping them | `weights/weight_reader` |
+| Merging LoRA adapters: target matching, INT8 scales, merge graphs | `model/adapter/lora_merge` |
+| Asynchronous uploads: queues, events, synchronization | `weights/weight_transfer` |
+| Capacity of devices from a snapshot | `weights/accounting` (pure) |
+| Source rules: which file data a weight reads, which weights share a copy | `weights/sources` (pure) |
+| Copying weights into another buffer type | `weights/weight_copy` |
+| When to prefetch | `core/segment_weight_pipeline` |
+| Capacity sum of weights, workspaces and buffer pools; trimming pools | `core/execution_engine` |
+
+`ModelManager` knows where every weight copy is and changes copies safely.
+Its `weights::WeightStore` (`weights/store`) owns the weight index, shared
+aliases and copy bindings, together with the `TensorState` and block types.
+`ModelManager` keeps its resources; a weight state holds its resource only as
+an opaque identifier, and the store asks the owner through one policy callback
+whether a weight's merge lives in a separate compute copy. Every
+change to a binding, block membership, lease, merged version or file source goes
+through the store; `TensorState` makes its residency transitions private to it.
+A new block joins residency when it is handed to the store. Snapshot generation
+and the execution of reclaim actions live in `model_manager_reclaim.cpp` and
+change copies only through the store. Capacity queries collect a snapshot of each
+device and evaluate it with `weights::evaluate_capacity()`, so a query reads no
+live state after the snapshot and uses the same reclaimable bytes as execution. The reader, the merger
+and the transfer receive destination tensors and never change bindings. The
+reader takes read targets (loader, file, sources, destination) and knows
+nothing about residency; staging from the model file reads straight into the
+compute copy. The merger receives the targets that need separate compute
+copies and returns success; `ModelManager` then records the merged epoch on
+those copies. Adapter weights stay registered with `ModelManager`.
+
+`prepare_params()` (`model_manager_prepare.cpp`) runs three phases. Allocation,
+reading, leases, merges and rollback share one lifecycle, so the flow and its
+intermediate state stay inside `ModelManager`: `ensure_copies()` loads and stages the
+weights, the LoRA layer groups the merge candidates by device, pairs INT8
+weights with their scales and merges, and `commit_merged()` records the version
+on the copies of finished groups. `ensure_copies()` succeeds only when every
+weight passes `ready_for_compute()`; a view is ready when the weight it views is,
+and a loading or staging failure reports whether device memory ran out.
+`lora_merge_target()` is the one place that decides which weights a resource's
+LoRA version merges into; `pending_merges()` groups the targets still missing
+the current version into units of a weight and its INT8 scale. The normal merge,
+the batched merge and the final check all use these units, and
+`merge_candidates()` only checks that each unit's copies are ready. The merge runs with every weight of the
+request leased, so its own reclaim keeps them. Each adapter merges its targets
+in batches of at most 4 GiB of F32 updates per graph; a batch that runs out of
+device memory, which happens before the graph writes anything, is halved and
+tried again. A batch writes its targets only after its graph succeeds, and later
+batches resume after the targets already written, so no adapter is merged twice.
+Capacity failures the merge recovers from are logged as information, not errors.
+
+If a single target does not fit next to the leased request, the merge first lets
+unmodified params copies yield and resumes from its existing progress. If that
+still does not fit, `merge_in_batches()` starts the unfinished work again from
+the originals with only one batch of targets and their INT8 scales leased at a time.
+The rest of the request stays unleased, so the merge can reclaim it. Completed
+compute copies that need to leave the device spill to RAM if there is room, and
+stage from that copy with their merged version intact. These RAM copies are
+protected until the request is ready. Disk-resident weights may use this temporary
+space too and drop it before the graph runs. A batch is split in half when its
+copies or its merge graph do not fit, down to a single target.
+This path needs host room for the merged copies that have to leave the device.
+It checks that no copy lost its merge. Weights merged in place are batched too.
+A request whose copies do not stage at all fails before entering this path,
+since its merged copies are as large and would not fit at the end either.
+The leases pass to the caller only when preparation
+succeeds. On a failure or an exception, a scope guard releases them and drops
+the copies the merge may have written: compute copies are discarded, and
+weights merged in place reload from the model file.
+
+`ExecutionEngine` asks `ModelManager::plan_reclaim()` for actions, executes them
+one at a time through `evict_compute_backend_block()`, and checks the real
+capacity after each one. It does not rank candidates itself. Each action keeps
+its kind (`ReclaimAction::Drop`, `Move` or `Release`) through execution. A move
+releases the copy when no lower location has room.
+
+Whole-graph capacity is summed by the engine. `fits_after_reclaim()` adds the
+idle workspaces of other sessions, which `ensure_capacity()` releases last, to
+the weights' reclaimable bytes. The segmentation decision uses this sum, so it
+counts the same memory that execution can free. The weight planner does not
+see workspaces and stays testable on its own.
+
+## Weight state
+
+Each `TensorState` records its copies instead of residency flags. The storage
+copy points at the `ParamsStorageBlock` holding the original, or a merge
+applied to it in place. The compute copy points at the `ComputeStagingBlock`
+the graph reads. Each copy carries the LoRA epoch merged into it.
+`loaded()`, `staged()` and `applied_epoch()` derive from these bindings. Views
+bind to a shared marker because their data lives in the base weight's
+allocation.
+
+The residency fields are private: copy bindings, epochs, file source,
+location, leases and the RAM cache of merged weights. They change only through
+transitions on `TensorState`:
+
+| Transition | When |
+| --- | --- |
+| `bind_storage`, `unbind_storage` | Load, shared reuse, release |
+| `bind_compute`, `unbind_compute` | Staging or prefetch activation, release |
+| `mark_merged`, `reset_merges` | LoRA merge into the bound copy, LoRA change |
+| `read_from_file` | The next compute copy reads the model file |
+| `move_to` | The storage copy moves, or the next load target changes |
+| `lease`, `release_lease`, `clear_leases` | Graph use |
+| `cache_merged`, `drop_merged_cache` | RAM cache of merged weights |
+
+Debug builds check after loads and `prepare_params()` that every binding
+matches block membership.
+
+## Snapshot
+
+`ModelManager::residency_snapshot()` describes one tier (a device or RAM) as
+`weights::Allocation`s. Each allocation is a real buffer and lists the weight
+`Copy`s it holds, so a buffer shared by several components counts once.
+
+| Kind | Meaning |
+| --- | --- |
+| `Compute` | Compute copy staged from a lower location or the model file |
+| `Storage` | Params storage: an original, or a merge applied in place |
+| `MergedCache` | RAM copy of merged LoRA weights |
+
+A copy records whether it is in use (`leased`), reserved by a prefetch, movable
+(file-backed, not split, view or custom-operator), `superseded` by another copy
+that serves the weight now, and whether a lower residency location exists. The
+model file is the implicit lowest location of every file-backed weight.
+
+An original is superseded when its merged LoRA copy is separate, or, in RAM,
+when a compute copy already holds it. Pins and protection of the weight do not
+keep a superseded copy. Originals that need a separate merged copy are
+allocated in storage blocks of their own, so a block of superseded originals
+never also holds weights the graph reads in place. On the device, the adapter
+weights of immediate LoRAs count as superseded while no merge uses them: they
+only feed merges, which load them again.
+
+## Planner
+
+`weights::plan_reclaim(snapshot, request)` returns ordered actions:
+
+| Action | Effect |
+| --- | --- |
+| `Drop` | Free a copy that has another copy or the model file below it |
+| `Move` | Copy to the next residency location, then free |
+| `Release` | Free the only copy above the model file |
+
+Each action reports its bytes and the bytes of the request's own weights that
+must load again afterwards. Which allocations an action may touch does not
+depend on the order, so capacity checks (`weights::reclaimable_bytes()`) sum the
+net bytes of the same actions without ordering them, and only execution
+(`ModelManager::plan_reclaim()`) sorts them and resolves their weights. Both
+use the same `weights::Request` to build the snapshot, so the segmentation
+decision and the executed reclaim follow one rule set. Reload bytes use the device allocation size,
+including padding and alignment.
+
+Device order:
+
+1. Superseded device originals of merged weights.
+2. Weights needed later by the current plan.
+3. Actions that reload none of the request's weights.
+4. Drops and releases before moves.
+5. The caller's preferred eviction order, then least recently used.
+
+RAM order: merged caches oldest first, then weights needed later, then shared
+compute copies, then least recently used.
+
+An evicted merged compute copy is saved to a RAM cache in the compute device's
+pinned host memory when it fits. Segment prefetch uploads a current cache
+asynchronously, like an offloaded original, and the uploaded copy keeps the
+cache's LoRA version. An INT8 weight is prefetched from its cache only together
+with its scale; otherwise it stages synchronously. An upload of an original
+records the original's merged version when it is queued, and activation drops
+the upload when a merge in place changed the original since.
+
+Request options cover the other callers:
+
+| Option | Used by |
+| --- | --- |
+| `required` | Segment weights that may leave and load again |
+| `protected_weights` | Weights that must stay, such as the next prefetch |
+| `allow_moves = false` | Making room for a move; victims are released |
+| `keep_resources`, `keep_next_use` | First loads. Originals of their own component and of components needed sooner stay, against both moves and releases |
+| `priority_limit` | RAM room for a demotion; victims must have a lower priority |
+
+Session cleanup and `assign_compute_backend()` select actions from the same
+candidates. Auto-fit's RAM estimate (`available_ram_for_fit()`) sums the RAM
+plan.
+
+## Call direction
+
+```
+ExecutionEngine --implements--> weights::CapacityProvider <--reserve-- ModelManager
+ExecutionEngine --plan_reclaim / evict_compute_backend_block--> ModelManager
+ModelManager::prepare_params --merge_candidates--> lora_merge
+```
+
+Weight allocations reserve device memory through `CapacityProvider`. The
+runtime implements it, sums weights, workspaces and buffer pools, and executes
+the residency layer's reclaim plan. `ModelManager` does not call the execution
+engine otherwise.
+
+## Execution
+
+`prepare_params()` loads, stages, and merges weights. A reclaim made for the
+request can release the request's own weights when the plan counts their reload
+bytes, so loading and staging repeat until a pass leaves every weight in place.
+During a merge, only compute copies and in-place targets are pinned.
+
+## Planned migration
+
+The remaining `ModelManager` files move into `src/weights/` without behavior
+changes, together with `device_residency_manager.h`,
+`core/segment_weight_pipeline` and the RAM and GPU budget helpers from
+`core/backend_fit`. `ExecutionEngine` then depends only on the residency
+interface header.
diff --git a/docs/dgl.md b/docs/dgl.md
index 0fe7af8..64a5558 100644
--- a/docs/dgl.md
+++ b/docs/dgl.md
@@ -1851,8 +1851,9 @@ mappings for in-place LoRA merges use allocated buffers.
#### Automatic weight placement
Set `backend` and `params_backend` on loaders in the script. The context's
-`auto_fit` setting chooses placement when `params_backend` is empty; it is
-enabled by default and cannot be overridden by individual loaders.
+`auto_fit` setting can move components to another GPU when `params_backend`
+is empty; it is enabled by default and cannot be overridden by individual
+loaders.
Each run prepares one weight-placement plan for the graph, including models
already cached in the context. Compilation tracks actual model use separately
from metadata queries and model captures. For example, `latent_shape` does not
@@ -1865,17 +1866,15 @@ constructing runners and uses the selected device consistently for default
loaders. Explicit backend choices and split layouts remain unchanged.
Before computation, the runtime constructs missing runner metadata without
-loading all weights, then combines registered parameter sizes, phase working
-sets, reclaimable cached buffers, device capacity and the context budgets.
-Automatic placement prioritizes diffusion models (`load_dit` / `load_unet`)
-over other components. It reserves their device storage first when the stage
-working set fits with other components offloaded. Larger models are considered
-first within each priority group.
-Explicit parameter backends and split layouts remain constraints. Automatic
-parameter storage can move between the compute device, CPU and disk on later
-runs without reconstructing a compatible model. Under pressure, weights with
-no remaining use or the farthest next use are reclaimed first. Idle weights
-remain cached when there is no pressure.
+loading all weights, then compares registered parameter sizes with device
+capacity and the context budgets. Parameters stay on their compute device and
+move to RAM, then disk, under pressure, as described in
+[weight residency](guides/backend.md#weight-residency). When the main GPU and
+RAM cannot hold all weights, components other than diffusion models
+(`load_dit` / `load_unet`) move to another GPU that holds all of their weights,
+lowest priority first. Explicit backends and split layouts remain constraints.
+Under pressure, weights with no remaining use or the farthest next use are
+reclaimed first. Idle weights remain cached when there is no pressure.
GGML sizes compute workspaces from the actual graphs built during execution.
The first plan reserves conservative workspace headroom; actual workspace
diff --git a/docs/guides/backend.md b/docs/guides/backend.md
index 8602cad..53397fc 100644
--- a/docs/guides/backend.md
+++ b/docs/guides/backend.md
@@ -9,8 +9,9 @@ DGL versions of the generation examples are linked below. Edit each script's
- `--backend` selects the runtime backend used to execute model graphs.
- `--params-backend` selects where model parameters are kept.
-If `--params-backend` is not set, auto-fit chooses parameter placement. With
-`--auto-fit off`, parameters use the same backend as their module runtime backend.
+If `--params-backend` is not set, parameters are kept on their module runtime
+backend and move to RAM or disk when it runs out of memory. Auto-fit can move
+components to another GPU.
## Syntax
@@ -91,11 +92,10 @@ applies to the dominant text encoder (`t5xxl` or the LLM); other modules accept
only a single device. If the module has no recognizable transformer blocks, the
assignment falls back to the first listed device.
-`--params-backend` accepts no device lists. If the module has no explicit
-params assignment, each block range's parameters are loaded directly to (and,
-with `--params-backend diffusion=disk`, released directly from) its own device;
-an explicit assignment such as `te=cpu` keeps the parameters on that backend
-and stages each range to its device on demand.
+`--params-backend` accepts no device lists. Each block range's parameters load
+directly to its own device. A params assignment such as `te=cpu` or
+`diffusion=disk` sets where the ranges move when device memory is needed, as
+described in [weight residency](#weight-residency).
Layer split uses the fixed graph-cut plan to assign blocks across devices, but
single-device segmented execution and next-segment prefetch are disabled for
@@ -153,9 +153,8 @@ the discrete GPU with the largest positive memory budget (the first device on a
tie), falling back to integrated GPUs when no discrete GPU has a positive budget.
An integrated GPU's shared system memory does not give it priority over a discrete
GPU. Explicit assignments such as `--backend Vulkan1` still select that device.
-It then derives parameter placements from the model metadata, each module's
-compute devices, and the remaining memory budgets. The chosen backend
-specifications are printed.
+It then checks whether the weights fit the remaining memory budgets and moves
+components to other GPUs when they do not. The plan is printed with `-v`.
```shell
sd-cli -m model.safetensors -p "a cat" --auto-fit on
@@ -185,62 +184,37 @@ With `--mmap`, device-backed mappings count toward these budgets at their full
mapped-file size, once per device buffer even when multiple parameter blocks
share it. Mappings retained in the loader cache continue to count.
-Components are considered in `diffusion`, `te`, `vae` order so that repeatedly
-used diffusion weights have priority. Each component's weights use the first
-storage location with enough remaining budget:
-
-1. The component's compute GPU, leaving estimated space for computation and weight staging.
-2. CPU RAM, reserving the larger of 2 GiB or 10% of available RAM for other work.
-3. Another GPU, choosing the one with the largest remaining budget that fits.
-4. Disk, reloading weights on demand.
-
-GPU cache space follows the same component priority. Before a lower-priority
-component can become permanently resident, the planner leaves room for the full
-weights and estimated compute space of higher-priority offloaded components.
-If offloaded diffusion already needs the entire main GPU budget, TE and VAE also
-use offloaded parameters. GPU copies remain cached across sampling steps while
-a component's execution is active and are released under memory pressure.
-Ending a component's execution releases its staged GPU copies, disk-backed
-weight buffers, temporary compute buffers and execution caches. Parameters
-assigned permanently to a backend remain resident. Hires model upscaling shares
-the runtime budget and can
-reclaim idle weight copies from other components.
-Reclamation releases idle compute buffers first, then cached weight allocations
-until the current work fits. Weights used by active computation or pending
+Auto-fit plans with whole-component weight sizes and a compute reserve of
+2 GiB for `diffusion` and `te` and 1 GiB for other components. Components keep
+their runtime backend as their params backend; weights that do not fit move to
+RAM, then disk, as described in [weight residency](#weight-residency). When the
+main GPU and the RAM available for weights cannot hold all weights, components
+other than `diffusion` move to another GPU, starting from the lowest priority in
+`diffusion`, `te`, `vae` order. A component moves only to a GPU whose remaining
+budget holds all of its weights and compute reserve, and it then runs there and
+keeps its weights there. Components with an explicit `--backend` assignment are
+not moved. A GPU exposed by several backends, such as CUDA and Vulkan, counts
+once.
+
+Hires model upscaling shares the runtime budget and can reclaim idle weight
+copies from other components. Weights used by active computation or pending
transfers stay protected.
-For CPU computation with disk-backed parameters, cached weights are released
-when execution ends so they do not accumulate in RAM across components.
-CPU parameter residency allows GPU weight caching; it does not force every
-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.
-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
-space. Storage on another module's GPU also leaves room for that module's work.
Auto-fit does not select multi-GPU layer/row computation itself. Explicit device
lists and `--split-mode` still control that computation. Before the runners have
built their split plans, auto-fit conservatively counts the full component size
-on each listed GPU when checking residency and cache space. This can offload
-parameters even when a split layout would fit; use `--auto-fit off` to keep the
-default split-device parameter placement.
+on each listed GPU when checking whether weights fit. This can move other
+components to another GPU even when a split layout would fit; use
+`--auto-fit off` to keep every component on its selected backend.
For example, a diffusion model whose full weights exceed the main GPU's budget
-can use `--backend diffusion=cuda0 --params-backend diffusion=cpu` when RAM is
-sufficient. Automatic graph segmentation can then load the required weights
-for each segment and reclaim idle GPU copies. `--disable-segmented-compute`
-still disables segmentation.
-
-Initial compute reserves are estimates (2 GiB for diffusion and text encoders,
-1 GiB for VAE); higher-priority placements also leave staging space for the
-largest weight tensor of each lower-priority offloaded component. Actual segment
-weights, compute buffers and caches must
-still fit the runner's capacity checks. Offloading weights does not guarantee
-that every resolution or frame count will fit, and auto-fit does not change a
-component to CPU computation solely because its full weights exceed VRAM.
+keeps the weights that fit on the GPU and stores the rest in RAM. Automatic graph
+segmentation then loads the required weights for each segment.
+`--disable-segmented-compute` still disables segmentation. Compute reserves are
+estimates. Actual segment weights, compute buffers and caches must still fit the
+runner's capacity checks, so not every resolution or frame count is guaranteed to
+fit, and auto-fit does not change a component to CPU computation solely because
+its full weights exceed VRAM.
If a VAE decode fails, decoding retries with spatial tiling even when `--auto-fit`
is off; supported video decoders try temporal tiling first and can then add
spatial tiling. Spatial retries use half-size tiles along each latent dimension.
@@ -410,7 +384,7 @@ sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend cpu
```
-This runs all modules on `cuda0`, but stores parameters in CPU RAM. During execution, parameters are moved to the runtime backend as needed.
+This runs all modules on `cuda0` and keeps parameters in CPU RAM. Each module copies the parameters it needs to `cuda0` while it runs.
For example:
@@ -419,9 +393,64 @@ sd-cli -m model.safetensors -p "a cat" --backend cuda0 --params-backend disk
```
-This runs all modules on `cuda0`, reloads parameters from the model file as needed, and releases those parameter buffers after use.
-
-Outside `--auto-fit`, `disk` is never selected implicitly. If `--params-backend` is not set, parameters use the runtime backend.
+This runs all modules on `cuda0` and reloads parameters from the model file instead of keeping them in RAM.
+
+`disk` is never selected implicitly. If `--params-backend` is not set, parameters are kept on the runtime backend.
+
+## Weight residency
+
+Weights load into their params backend on first use. When a location runs out
+of memory, weights move down a residency chain:
+
+| `--params-backend` | Residency chain |
+| --- | --- |
+| Not set, or the runtime backend | runtime device, RAM, disk |
+| Another GPU | that GPU, RAM, disk |
+| `cpu` | RAM, disk |
+| `disk` | disk |
+
+With `--mmap`, weights read from the mapped model file skip RAM because
+reloads come from the page cache. Weights used by an operation that the compute
+device cannot run, such as INT8 tensorwise embeddings, are stored in RAM.
+
+A first load does not displace weights already resident in the params backend
+unless they belong to another component that is needed no sooner. Otherwise the
+new weights start at the next location on the chain. With CPU params and GPU
+compute, weights that do not fit in RAM can load directly from the model file
+into their compute buffers. Weights that need host storage still require RAM.
+
+When a weight leaves a location, it is released if the next location already
+holds a copy, and copied there otherwise. If the next location lacks capacity,
+weights there with a lower priority are released to make room; they are not
+copied further. If room still cannot be made, the weight moves on to the
+following location. Reaching disk releases the weight without writing to the
+model file. Weights needed sooner by the current plan, then more recently used
+weights, have priority.
+
+Weights stored away from the compute device are copied to it while a component
+runs. These copies are released when the component finishes, so `cpu`,
+another GPU, or `disk` keeps device memory free between components. Copies of
+weights whose params backend is the compute device, made after those weights
+moved to RAM or disk, stay until device memory is needed. When device memory is
+needed, GPU originals of weights with a separate merged LoRA copy move first,
+then copies that can be dropped, then resident weights that must be copied to
+the next location, then idle compute buffers. The capacity check that decides
+whether a graph needs segmentation counts the same actions.
+
+`--eager-load` reads weights when a model loads instead of on first use. Each
+weight takes the highest location on its chain with free capacity, leaving a
+2 GiB compute reserve on GPUs, without releasing resident weights. Weights that
+do not fit load on first use.
+
+Weights with an immediately applied LoRA follow the same chain. Releasing a
+merged weight to disk discards the merge, and the next use merges again. When
+immediate LoRA application stages a separate compute copy of shared weights,
+the unmerged originals also follow the chain; if no location can hold them,
+compute copies load from the model file. Later LoRA variants reuse cached
+originals when available. When merged copies are released from the GPU,
+available RAM can cache them for later use unless the weights prefer disk.
+During a batched immediate merge, disk-resident weights can use temporary RAM
+to retain their merged values until the graph's weights are ready.
Per-module assignments can be mixed:
@@ -448,7 +477,7 @@ uses one shared CPU backend for both `te` and `vae` runtime execution.
Runtime and parameter assignments also share the same backend cache. If `--backend diffusion=cuda0` and `--params-backend diffusion=cuda0` resolve to the same device, both use the same backend instance.
-`--params-backend disk` does not create a separate backend instance. Parameters are loaded lazily using the module runtime backend.
+`--params-backend disk` does not create a separate backend instance. Parameters are loaded on use with the module runtime backend.
`SDBackendManager` owns the backend instances and frees them when the context or upscaler is destroyed. Model runners receive non-owning runtime and parameter backend pointers and do not free them.
@@ -469,7 +498,7 @@ The example CLI/server still accepts these older CPU placement flags as compatib
--params-backend '*=cpu'
```
-Because this default is inserted first, later explicit `--params-backend` entries can still override it, for example `--offload-to-cpu --params-backend te=disk` keeps non-TE parameters on CPU and reloads TE parameters from disk.
+Because this default is inserted first, later explicit `--params-backend` entries can still override it, for example `--offload-to-cpu --params-backend te=disk` makes non-TE parameters prefer CPU RAM and TE parameters prefer disk.
Library callers should set `backend` and `params_backend` directly. `sd_ctx_params_init()`
enables `auto_fit` by default; a nonempty `params_backend` assignment disables it.
diff --git a/docs/guides/c_api.md b/docs/guides/c_api.md
index e456c00..0ee98d3 100644
--- a/docs/guides/c_api.md
+++ b/docs/guides/c_api.md
@@ -65,7 +65,11 @@ cleanup:
`sd_ctx_create()` retains the model configuration. The first generation call
loads the components it needs and reports any loading errors through its return
status. Weight residency follows `eager_load` and the memory budgets. Capability
-queries can probe the model family and reuse the detected type.
+queries can probe the model family and reuse the detected type. Components stay
+loaded between generation calls. With `run_once`, read when the context is
+created, each component is released after its last use in a generation run
+instead, and every run, including each image of a batch, loads the components
+again.
Use `sd_ctx_set_model_options()` on an idle context to replace its model
configuration. It copies the options and resets model detection. Later
@@ -81,10 +85,9 @@ file-access callbacks for generated programs and scripts through
`sd_ctx_set_file_access_callback()` and `sd_dgl_ctx_set_file_access_callback()`
respectively.
-Use `sd_dgl_ctx_release_staging()` to release idle GPU staging copies backed by
-RAM weights. Use `sd_dgl_ctx_unload_models()` to release cached model components
-and reload them on demand. Both clear idle buffer caches on supported backends
-and return `SD_STATUS_BUSY` while the context is running a script or generation.
+Use `sd_dgl_ctx_unload_models()` to release cached model components and reload
+them on demand. It clears idle buffer caches on supported backends and returns
+`SD_STATUS_BUSY` while the context is running a script or generation.
Use `sd_generate_video()` with options from `sd_vid_gen_opt_create()` to generate video. Its result
exposes frames through the same image accessors, optional audio through
@@ -458,6 +461,7 @@ For SDXL's bundled VAE (no `vae_path`), generation emits
| `ref_videos` | `videos` | video |
| `rng_type` | `string` | context |
| `rpc_servers` | `string` | context |
+| `run_once` | `bool` | context |
| `sage_attn` | `bool` | context |
| `sample.args` | `string` | image, video |
| `sample.eta` | `float` | image, video |
diff --git a/docs/guides/int8_convrot.md b/docs/guides/int8_convrot.md
index 07ee5de..f67a467 100644
--- a/docs/guides/int8_convrot.md
+++ b/docs/guides/int8_convrot.md
@@ -111,9 +111,19 @@ Immediate mode merges an adapter into INT8 tensorwise weights on first use.
For convrot weights, sd.cpp rotates the adapter update before adding it to the
dequantized weights. It then recalculates the weight
scales and requantizes the result to INT8. The merge runs on the selected
-backend when it supports the operation, with ggml's usual CPU fallback. The
-additional quantization step can change the output compared with runtime
-application.
+backend when it supports the operation, with ggml's usual CPU fallback.
+
+Requantizing can drop an adapter's effect entirely. Each row of an INT8 weight
+can only change in steps of its scale, the row's largest magnitude divided by
+127. The original values lie exactly on those steps, so while the row's scale
+stays the same, an update smaller than half a step rounds back to the original
+INT8 value. The scale changes only when the update changes the row's largest
+magnitude; the new scale then moves every value in the row, so small updates
+can shift the result even though each one alone would round away.
+Many adapters, such as distillation LoRAs with small updates, fall below that
+threshold for nearly every weight; immediate mode then produces almost the same
+output as running without the adapter. Larger updates survive only partly. Use
+`--lora-apply-mode at_runtime` when the adapter must match its intended effect.
The shared CUDA/HIP/MUSA convrot activation paths support H64 and H256.
diff --git a/docs/guides/performance.md b/docs/guides/performance.md
index 243b5f9..edbd6e2 100644
--- a/docs/guides/performance.md
+++ b/docs/guides/performance.md
@@ -114,7 +114,7 @@ Using `--offload-to-cpu` allows you to offload weights to the CPU, saving VRAM w
## Use params backend to reduce VRAM or RAM usage.
-`--params-backend` controls where model parameters are kept. If it is not set, auto-fit chooses parameter placement while preserving `--backend`. With `--auto-fit off`, parameters use the same backend as `--backend`, so a GPU runtime backend also keeps parameters in VRAM.
+`--params-backend` controls where model parameters are kept. If it is not set, parameters are kept on the `--backend` device, and weights that do not fit move to RAM, then disk. See [weight residency](backend.md#weight-residency).
Use CPU params to reduce VRAM usage:
diff --git a/docs/models/lora.md b/docs/models/lora.md
index e1e75c3..08265ac 100644
--- a/docs/models/lora.md
+++ b/docs/models/lora.md
@@ -84,7 +84,13 @@ weights. For scripts, see
The **immediately** mode may have precision and compatibility issues with quantized parameters, but it usually offers faster inference speed and, in some cases, lower memory usage.
For INT8 tensorwise and convrot weights, **immediately** merges and requantizes
-the affected weights. See the [INT8 convrot guide](../guides/int8_convrot.md).
+the affected weights. Requantizing can round away updates smaller than half an INT8
+step, so adapters with small updates can lose most or all of their effect; use
+**at_runtime** for them. See the [INT8 convrot guide](../guides/int8_convrot.md).
+When the weights fill the `--max-vram` budget, **immediately** can merge a few
+weights at a time. Merged weights that have to leave VRAM use temporary RAM,
+including with `--params-backend disk`. If the merge cannot fit, increasing the
+memory budget or choosing **at_runtime** can help.
In contrast, the **at_runtime** mode provides better compatibility and higher precision, but inference may be slower and memory usage may be higher in some cases.
## Notes and limitations
diff --git a/examples/cli/README.md b/examples/cli/README.md
index a43e22c..d8c5a0f 100644
--- a/examples/cli/README.md
+++ b/examples/cli/README.md
@@ -51,6 +51,9 @@ DGL mode accepts the same logging options and sends logs to stderr.
Weight loading displays a progress bar with transfer speed; sampling displays
its step progress. Context progress callbacks remain active during loading.
`--run-once on|off` controls model release after last use and defaults to `on`.
+Image and video generation release each model after its last use as well,
+except for image batches (`-b` greater than 1), which keep models loaded across
+the batch.
`--flash-attn on|off|auto` defaults to `auto`, selecting flash attention for each
compute backend during context creation. See [Backend selection](../../docs/guides/backend.md#flash-attention---flash-attn-onoffauto)
diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp
index e3b7202..a40c9fc 100644
--- a/examples/cli/main.cpp
+++ b/examples/cli/main.cpp
@@ -759,6 +759,9 @@ int main(int argc, const char* argv[]) {
}
}
+ // A single generation run needs no component cache; each model is released after its last use.
+ if (cli_params.mode == VID_GEN || (cli_params.mode == IMG_GEN && gen_params.batch_count.value_or(1) <= 1))
+ ctx_params.run_once = true;
SDOptPtr sd_ctx_params = ctx_params.to_context_opt();
SDImageVec results;
diff --git a/examples/common/common.cpp b/examples/common/common.cpp
index cf400eb..9d9ad70 100644
--- a/examples/common/common.cpp
+++ b/examples/common/common.cpp
@@ -571,7 +571,7 @@ ArgOptions SDContextParams::get_options() {
true, &disable_segmented_compute},
{"",
"--eager-load",
- "load all params into the params backend at model-load time instead of lazily on first use (defaults to false)",
+ "read params at model-load time into the highest residency location with free capacity instead of on first use (defaults to false)",
true, &eager_load},
{"",
"--force-sdxl-vae-conv-scale",
@@ -747,8 +747,8 @@ 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). "
+ "on|off (default: on). Preserve --backend (otherwise select one GPU) and move components to another GPU "
+ "when the weights do not fit the main GPU and RAM (--max-vram limits GPU budgets). "
"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);
@@ -1056,6 +1056,7 @@ SDOptPtr SDContextParams::to_context_opt() {
opt.set_bool("disable_segmented_compute", disable_segmented_compute);
opt.set_bool("batched_cfg", batched_cfg);
opt.set_bool("eager_load", eager_load);
+ opt.set_bool("run_once", run_once);
if (backend || !effective_backend.empty())
opt.set_string("backend", effective_backend);
if (params_backend || !effective_params_backend.empty())
diff --git a/examples/common/common.h b/examples/common/common.h
index cddfaf0..509f673 100644
--- a/examples/common/common.h
+++ b/examples/common/common.h
@@ -163,6 +163,7 @@ struct SDContextParams {
std::optional<bool> disable_prefetch;
std::optional<bool> disable_segmented_compute;
std::optional<bool> eager_load;
+ std::optional<bool> run_once;
std::optional<bool> batched_cfg;
std::optional<std::string> backend;
std::optional<std::string> params_backend;
diff --git a/examples/server/README.md b/examples/server/README.md
index a42f2d0..bde6dd5 100644
--- a/examples/server/README.md
+++ b/examples/server/README.md
@@ -504,17 +504,16 @@ Startup fails if an access option is missing its value, a list is empty
| Option | Default | Memory released when idle |
| --- | --- | --- |
-| `--weight-staging-ttl <seconds>` | `-1` | GPU staging copies of weights backed by RAM, including components placed on CPU by `--params-backend cpu` or auto-fit. The next request uploads the needed weights from RAM. |
| `--weight-residency-ttl <seconds>` | `-1` | Cached model components, including RAM weights, GPU weights, staging copies, and component caches. The next request loads the needed components from their files. |
-Both options also clear idle reusable buffers on supported backends after
-releasing weights.
+The option also clears idle reusable buffers on supported backends after
+releasing weights. GPU copies of weights stored in RAM, on another GPU, or on
+disk are released when each component finishes, so they need no idle timer.
-For either option, `-1` disables release, `0` releases as soon as the shared
+`-1` disables release, `0` releases as soon as the shared
context is idle, and a positive integer sets the idle time in seconds. The
timer starts when the last job finishes. Running and queued generation or DGL
-jobs defer release. Status and progress requests do not reset the timer. If
-both deadlines are due, the server unloads the model components in one step.
+jobs defer release. Status and progress requests do not reset the timer.
The configured model and the model catalog remain available after unloading.
### Logging
diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp
index 3216e01..329cf29 100644
--- a/examples/server/async_jobs.cpp
+++ b/examples/server/async_jobs.cpp
@@ -718,7 +718,7 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param
: fs::weakly_canonical(fs::absolute(fs::u8path(params.output_dir)));
if (output_root.has_relative_path() && !output_root.has_filename())
output_root = output_root.parent_path();
- policy = {get_model_roots(params), output_root, {}, {}};
+ policy = {get_model_roots(params), output_root, {}, {}};
for (const auto* directory : {&config.lora_model_dir, &config.hires_upscalers_dir})
if (!directory->empty())
policy.models.push_back(make_model_root(fs::u8path(*directory), false));
@@ -769,8 +769,6 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime,
void AsyncJobManager::record_context_job_completion(const SDSvrParams& params) {
const auto now = std::chrono::steady_clock::now();
- if (params.weight_staging_ttl >= 0)
- staging_deadline = now + std::chrono::seconds(params.weight_staging_ttl);
if (params.weight_residency_ttl >= 0)
residency_deadline = now + std::chrono::seconds(params.weight_residency_ttl);
}
@@ -780,7 +778,7 @@ static void wait_for_job(ServerRuntime& runtime, std::unique_lock<std::mutex>& l
using Clock = std::chrono::steady_clock;
const auto disabled = Clock::time_point::max();
while (!manager.stop && manager.queue.empty()) {
- const auto deadline = std::min(manager.staging_deadline, manager.residency_deadline);
+ const auto deadline = manager.residency_deadline;
if (deadline == disabled || manager.synchronous_jobs != 0) {
manager.cv.wait(lock);
continue;
@@ -792,18 +790,15 @@ static void wait_for_job(ServerRuntime& runtime, std::unique_lock<std::mutex>& l
}
// Keep job admission serialized with the idle check and the DGL release.
- const bool unload = now >= manager.residency_deadline;
auto* ctx = sd_ctx_get_dgl_ctx(runtime.sd_ctx);
- const auto status = unload ? sd_dgl_ctx_unload_models(ctx) : sd_dgl_ctx_release_staging(ctx);
+ const auto status = sd_dgl_ctx_unload_models(ctx);
if (status == SD_STATUS_BUSY) {
manager.cv.wait_for(lock, std::chrono::milliseconds(100));
continue;
}
if (status != SD_STATUS_OK)
LOG_WARN("idle weight release failed: %s", sd_dgl_error());
- if (unload)
- manager.residency_deadline = disabled;
- manager.staging_deadline = disabled;
+ manager.residency_deadline = disabled;
}
}
diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h
index 14c491d..0f8b932 100644
--- a/examples/server/async_jobs.h
+++ b/examples/server/async_jobs.h
@@ -87,7 +87,6 @@ struct AsyncJobManager {
int64_t failed_ttl_seconds = 600;
size_t synchronous_jobs = 0;
- std::chrono::steady_clock::time_point staging_deadline = std::chrono::steady_clock::time_point::max();
std::chrono::steady_clock::time_point residency_deadline = std::chrono::steady_clock::time_point::max();
void record_context_job_completion(const SDSvrParams& params);
diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp
index 6853acd..c513ab9 100644
--- a/examples/server/runtime.cpp
+++ b/examples/server/runtime.cpp
@@ -331,11 +331,6 @@ ArgOptions SDSvrParams::get_options() {
options.manual_options = {
{"-h", "--help", "show this help message and exit", on_help_arg},
- {"", "--weight-staging-ttl",
- "idle seconds before releasing GPU staging copies of RAM weights (-1 disabled, 0 immediate; default: -1)",
- [this](int argc, const char** argv, int index) {
- return parse_weight_ttl(argc, argv, index, weight_staging_ttl);
- }},
{"", "--weight-residency-ttl",
"idle seconds before unloading model components from RAM and VRAM (-1 disabled, 0 immediate; default: -1)",
[this](int argc, const char** argv, int index) {
@@ -397,7 +392,6 @@ std::string SDSvrParams::to_string() const {
<< " listen_port: \"" << listen_port << "\",\n"
<< " max_pending_jobs: " << max_pending_jobs << ",\n"
<< " completed_ttl_seconds: " << completed_ttl_seconds << ",\n"
- << " weight_staging_ttl: " << weight_staging_ttl << ",\n"
<< " weight_residency_ttl: " << weight_residency_ttl << ",\n"
<< " serve_html_path: \"" << serve_html_path << "\",\n"
<< " dgl_dir: \"" << dgl_dir << "\",\n"
diff --git a/examples/server/runtime.h b/examples/server/runtime.h
index 7989104..7c20ec2 100644
--- a/examples/server/runtime.h
+++ b/examples/server/runtime.h
@@ -24,7 +24,6 @@ struct SDSvrParams {
int listen_port = 1234;
int max_pending_jobs = 64;
int completed_ttl_seconds = 600;
- int weight_staging_ttl = -1;
int weight_residency_ttl = -1;
std::string serve_html_path;
std::string dgl_dir = "dgl";
diff --git a/include/stable-diffusion.h b/include/stable-diffusion.h
index c41818a..9829afe 100644
--- a/include/stable-diffusion.h
+++ b/include/stable-diffusion.h
@@ -365,10 +365,6 @@ SD_API void sd_dgl_ctx_free(sd_dgl_ctx_t* ctx);
// Threading, placement and weight-loading options invalidate cached models when changed.
SD_API bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value);
-// Releases idle GPU staging buffers that have RAM originals.
-// Clears idle buffer caches on supported backends.
-// Returns SD_STATUS_BUSY during DGL execution or generation.
-SD_API sd_status_t sd_dgl_ctx_release_staging(sd_dgl_ctx_t* ctx);
// Unloads cached model components and clears idle buffer caches on supported backends.
// The context keeps its settings and callbacks.
// Subsequent requests reload components as needed. Returns SD_STATUS_BUSY during execution.
diff --git a/src/api/generation.cpp b/src/api/generation.cpp
index 5de121d..d02d8a7 100644
--- a/src/api/generation.cpp
+++ b/src/api/generation.cpp
@@ -26,7 +26,7 @@ namespace sd::api {
}
GenerationContext::GenerationContext(const sd_opt_t* source, Operation purpose)
- : model(copy_options(source), purpose) {
+ : model(copy_options(source), purpose), execution(!model.config.context.run_once) {
const auto& settings = model.config.context;
execution.set("n_threads", std::to_string(settings.n_threads));
if (settings.linear_type)
diff --git a/src/api/options.cpp b/src/api/options.cpp
index 4f1970a..f056647 100644
--- a/src/api/options.cpp
+++ b/src/api/options.cpp
@@ -321,6 +321,7 @@ static void add_context_specs(std::vector<ParamSpec>& specs) {
ctx.choice("prediction", &sd::ContextConfig::prediction, str_to_prediction, PREDICTION_COUNT, true);
ctx.choice("rng_type", &sd::ContextConfig::rng_type, str_to_rng_type, RNG_TYPE_COUNT, true);
ctx.string("rpc_servers", &sd::ContextConfig::rpc_servers);
+ ctx.boolean("run_once", &sd::ContextConfig::run_once);
ctx.boolean("sage_attn", &sd::ContextConfig::sage_attn);
ctx.choice("sampler_rng_type", &sd::ContextConfig::sampler_rng_type, str_to_rng_type, RNG_TYPE_COUNT, true);
ctx.string("split_mode", &sd::ContextConfig::split_mode);
diff --git a/src/api/upscaler.cpp b/src/api/upscaler.cpp
index 2e2aa05..a7e70db 100644
--- a/src/api/upscaler.cpp
+++ b/src/api/upscaler.cpp
@@ -53,7 +53,7 @@ sd_status_t sd_upscaler_create(const sd_upscaler_opt_t* options, sd_upscaler_t**
sd::dgl::RunEventsScope scope(events);
sd::dgl::RunState state{result->context.execution, events};
sd::dgl::RunPlan plan(result->program, state);
- result->model = plan.load_resource(*resource.operation, arguments).as<sd::dgl::models::ImageUpscaler>();
+ result->model = plan.load_resource(resource.expression, *resource.operation, arguments).as<sd::dgl::models::ImageUpscaler>();
if (result->model->get_scale() <= 0)
throw sd::dgl::Error(SD_STATUS_LOAD_FAILED, "invalid image upscaler scale");
*out = result.release();
diff --git a/src/config.h b/src/config.h
index c93e84a..d0acd93 100644
--- a/src/config.h
+++ b/src/config.h
@@ -106,7 +106,8 @@ namespace sd {
const char* max_vram{}; // Optional per-device GiB budget for managed weights and runner buffers; 0 uses live free VRAM without an explicit budget
const char* max_ram{};
bool disable_prefetch{}; // Disable asynchronous next-segment weight prefetch
- bool eager_load{}; // Load all params into the params backend at model-load time instead of lazily on first use
+ bool eager_load{}; // Read params at model-load time into free residency capacity instead of on first use
+ bool run_once{}; // Release each model after its last use in a generation run; read at context creation
const char* backend{};
const char* params_backend{};
const char* split_mode{}; // weight distribution for multi-device modules: layer (default) or row, or per-module assignments e.g. "diffusion=row"
diff --git a/src/core/backend_fit.cpp b/src/core/backend_fit.cpp
index 9df9c61..35e32f2 100644
--- a/src/core/backend_fit.cpp
+++ b/src/core/backend_fit.cpp
@@ -6,7 +6,8 @@
#include <cstddef>
#include <cstdint>
#include <fstream>
-#include <utility>
+#include <map>
+#include <set>
#include <vector>
#if defined(_WIN32)
@@ -21,27 +22,13 @@
#include "core/ggml_extend_backend.h"
#include "core/util.h"
#include "ggml-backend.h"
-#include "name_conversion.h"
namespace sd::backend_fit {
static constexpr int64_t MiB = 1024ll * 1024;
- enum class ComponentKind {
- DIT,
- CONDITIONER,
- VAE,
- };
-
- struct Component {
- ComponentKind kind;
- const char* name;
- int64_t params_bytes = 0;
- int64_t reserve_bytes = 0;
- int64_t staging_bytes = 0;
- };
-
struct Device {
+ ggml_backend_dev_t device = nullptr;
std::string name;
std::string description;
int64_t free_bytes = 0;
@@ -49,102 +36,22 @@ namespace sd::backend_fit {
enum ggml_backend_dev_type type = GGML_BACKEND_DEVICE_TYPE_GPU;
};
- enum class ParamsLocation {
- MAIN_GPU,
- CPU,
- OTHER_GPU,
- DISK,
- };
-
- struct Decision {
- ParamsLocation params_location = ParamsLocation::DISK;
- size_t params_device = SIZE_MAX;
- };
-
- struct Runtime {
- std::string name;
- std::vector<size_t> devices;
- };
-
- struct Plan {
- bool valid = false;
- size_t main_device = SIZE_MAX;
- std::vector<Runtime> runtimes;
- std::vector<Decision> decisions;
- };
-
- static bool classify_tensor(const std::string& name, ComponentKind& out) {
- auto contains = [&](const char* s) { return name.find(s) != std::string::npos; };
-
- if (is_cond_stage_model_name(name)) {
- out = ComponentKind::CONDITIONER;
- return true;
- }
- if (contains("model.diffusion_model.") || contains("unet.") || name.rfind("diffusion.", 0) == 0) {
- out = ComponentKind::DIT;
- return true;
- }
- if (contains("first_stage_model.") ||
- name.rfind("vae.", 0) == 0 ||
- name.rfind("tae.", 0) == 0) {
- out = ComponentKind::VAE;
- return true;
- }
- if (contains("text_encoders") ||
- contains("cond_stage_model") ||
- contains("te.text_model.") ||
- contains("conditioner") ||
- name.rfind("text_encoder.", 0) == 0 ||
- contains(".aggregate_embed.")) {
- out = ComponentKind::CONDITIONER;
- return true;
- }
- return false;
- }
-
- static std::vector<Component> estimate_components(ModelLoader& loader, ggml_type override_wtype, const char* standalone_name = nullptr) {
- int64_t bytes[3] = {0, 0, 0};
- int64_t largest_tensor[3] = {0, 0, 0};
- for (const auto& [name, stored_tensor] : loader.get_tensor_storage_map()) {
- TensorStorage ts = stored_tensor;
- ComponentKind kind = ComponentKind::DIT;
- if (!standalone_name && !classify_tensor(ts.name, kind)) {
- continue;
- }
- if (ts.expected_type != GGML_TYPE_COUNT) {
- ts.type = ts.expected_type;
- } else if (override_wtype != GGML_TYPE_COUNT && loader.tensor_should_be_converted(ts, override_wtype)) {
- ts.type = override_wtype;
- }
- const int64_t tensor_bytes = (int64_t)ts.nbytes() + 64;
- bytes[int(kind)] += tensor_bytes;
- largest_tensor[int(kind)] = std::max(largest_tensor[int(kind)], tensor_bytes);
- }
-
- return {
- {ComponentKind::DIT, standalone_name ? standalone_name : "DiT", bytes[int(ComponentKind::DIT)], 2048 * MiB, largest_tensor[int(ComponentKind::DIT)]},
- {ComponentKind::CONDITIONER, "Conditioner", bytes[int(ComponentKind::CONDITIONER)], 2048 * MiB, largest_tensor[int(ComponentKind::CONDITIONER)]},
- {ComponentKind::VAE, "VAE", bytes[int(ComponentKind::VAE)], 1024 * MiB, largest_tensor[int(ComponentKind::VAE)]},
- };
- }
-
static std::string budget_key(std::string name) {
std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return (char)std::tolower(c); });
return name;
}
static std::vector<Device> enumerate_gpu_devices(const sd::ggml_graph_cut::MaxVramAssignment& budgets,
- bool include_other_devices,
const AvailableVRAM& available_vram) {
std::vector<Device> out;
for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
ggml_backend_dev_t dev = ggml_backend_dev_get(i);
const auto type = ggml_backend_dev_type(dev);
- if (type != GGML_BACKEND_DEVICE_TYPE_GPU && type != GGML_BACKEND_DEVICE_TYPE_IGPU &&
- (!include_other_devices || type == GGML_BACKEND_DEVICE_TYPE_CPU)) {
+ if (type != GGML_BACKEND_DEVICE_TYPE_GPU && type != GGML_BACKEND_DEVICE_TYPE_IGPU) {
continue;
}
Device device;
+ device.device = dev;
device.name = ggml_backend_dev_name(dev);
device.description = ggml_backend_dev_description(dev);
device.type = type;
@@ -233,307 +140,44 @@ namespace sd::backend_fit {
return SIZE_MAX;
}
- static Plan compute_plan(const std::vector<Component>& components,
- const std::vector<Device>& devices,
- int64_t ram_budget_bytes,
- const std::vector<Runtime>& runtimes = {}) {
- Plan plan;
- plan.main_device = select_main_device(devices);
- plan.runtimes = runtimes;
- if (plan.runtimes.empty()) {
- if (plan.main_device == SIZE_MAX) {
- return plan;
- }
- plan.runtimes.resize(components.size(), {devices[plan.main_device].name, {plan.main_device}});
- }
-
- std::vector<size_t> order(components.size());
- for (size_t ci = 0; ci < components.size(); ++ci) {
- order[ci] = ci;
- }
- std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {
- return components[a].kind < components[b].kind;
- });
-
- std::vector<int64_t> remaining;
- for (const Device& device : devices) {
- remaining.push_back(std::max<int64_t>(device.budget_bytes, 0));
- }
- ram_budget_bytes = std::max<int64_t>(ram_budget_bytes, 0);
- plan.decisions.resize(components.size());
-
- auto uses_device = [&](size_t ci, size_t di) {
- const auto& runtime_devices = plan.runtimes[ci].devices;
- return std::find(runtime_devices.begin(), runtime_devices.end(), di) != runtime_devices.end();
- };
- auto headroom_for = [&](size_t ci, size_t di) {
- // Higher-priority offloaded weights need cache space on their compute devices.
- int64_t headroom = 0;
- for (size_t other = 0; other < components.size(); ++other) {
- if (components[other].params_bytes == 0 || !uses_device(other, di)) {
- continue;
- }
- const bool resident = other == ci || plan.decisions[other].params_location == ParamsLocation::MAIN_GPU;
- const int64_t cached_weights = components[other].kind < components[ci].kind
- ? components[other].params_bytes
- : components[other].staging_bytes;
- headroom = std::max(headroom, components[other].reserve_bytes +
- (resident ? 0 : cached_weights));
- }
- return headroom;
- };
-
- for (size_t ci : order) {
- const Component& comp = components[ci];
- Decision& decision = plan.decisions[ci];
- if (comp.params_bytes == 0) {
- continue;
- }
-
- const auto& runtime_devices = plan.runtimes[ci].devices;
- const bool fits_runtime = !runtime_devices.empty() &&
- std::all_of(runtime_devices.begin(), runtime_devices.end(), [&](size_t di) {
- const int64_t headroom = headroom_for(ci, di);
- return headroom <= remaining[di] && comp.params_bytes <= remaining[di] - headroom;
- });
- if (fits_runtime) {
- decision.params_location = ParamsLocation::MAIN_GPU;
- decision.params_device = runtime_devices.front();
- // Exact split allocations are unavailable until the runners build their plans.
- for (size_t di : runtime_devices) {
- remaining[di] -= comp.params_bytes;
- }
- continue;
- }
- if (comp.params_bytes <= ram_budget_bytes) {
- decision.params_location = ParamsLocation::CPU;
- ram_budget_bytes -= comp.params_bytes;
- continue;
- }
- if (runtime_devices.empty()) {
- continue;
- }
-
- size_t best = SIZE_MAX;
- for (size_t di = 0; di < devices.size(); ++di) {
- const int64_t headroom = headroom_for(ci, di);
- if (!uses_device(ci, di) && headroom <= remaining[di] && comp.params_bytes <= remaining[di] - headroom &&
- (best == SIZE_MAX || remaining[di] > remaining[best])) {
- best = di;
- }
- }
- if (best != SIZE_MAX) {
- decision.params_location = ParamsLocation::OTHER_GPU;
- decision.params_device = best;
- remaining[best] -= comp.params_bytes;
- }
- }
- plan.valid = true;
- return plan;
- }
-
- static std::string params_backend_name(const Decision& decision, const std::vector<Device>& devices) {
- switch (decision.params_location) {
- case ParamsLocation::MAIN_GPU:
- case ParamsLocation::OTHER_GPU:
- return devices[decision.params_device].name;
- case ParamsLocation::CPU:
- return "cpu";
- case ParamsLocation::DISK:
- return "disk";
- }
- return "disk";
- }
-
- static void print_plan(const Plan& plan,
- const std::vector<Component>& components,
- const std::vector<Device>& devices,
- int64_t free_ram,
- int64_t ram_budget) {
- LOG_INFO("auto-fit plan:");
- LOG_INFO(" devices:");
- for (const Device& device : devices) {
- LOG_INFO(" %-12s %-32s free %6lld MiB, budget %6lld MiB",
- device.name.c_str(), device.description.c_str(),
- (long long)(device.free_bytes / MiB), (long long)(device.budget_bytes / MiB));
- }
- if (free_ram < 0) {
- LOG_WARN("auto-fit: available RAM is unknown; skipping CPU parameter residency");
- } else {
- LOG_INFO(" RAM free %6lld MiB, params budget %6lld MiB",
- (long long)(free_ram / MiB), (long long)(ram_budget / MiB));
- }
- LOG_INFO(" compute-device weight cache priority: diffusion > te > vae");
- LOG_INFO(" components (params: compute device -> RAM -> other GPU -> disk):");
- for (size_t ci = 0; ci < components.size(); ++ci) {
- const Component& comp = components[ci];
- if (comp.params_bytes == 0) {
- continue;
- }
- const std::string params = plan.decisions[ci].params_location == ParamsLocation::MAIN_GPU
- ? plan.runtimes[ci].name
- : params_backend_name(plan.decisions[ci], devices);
- LOG_INFO(" %-12s params %6lld MiB, compute reserve %5lld MiB -> compute %s, params %s",
- comp.name, (long long)(comp.params_bytes / MiB), (long long)(comp.reserve_bytes / MiB),
- plan.runtimes[ci].name.c_str(), params.c_str());
- }
- }
-
- static void append_assignment(std::string& spec, const char* key, const std::string& value) {
- if (!spec.empty()) {
- spec += ",";
+ // Backends of one card share its memory, so the tightest --max-vram cap applies to all of them.
+ static std::vector<Device> physical_budgets(const sd::ggml_graph_cut::MaxVramAssignment& budgets, const AvailableVRAM& available_vram) {
+ auto devices = enumerate_gpu_devices(budgets, available_vram);
+ std::map<std::string, int64_t> tightest;
+ for (const auto& device : devices) {
+ const auto added = tightest.emplace(physical_device_key(device.device), device.budget_bytes);
+ if (!added.second)
+ added.first->second = std::min(added.first->second, device.budget_bytes);
}
- spec += key;
- spec += "=";
- spec += value;
- }
-
- static const char* module_key(ComponentKind kind) {
- switch (kind) {
- case ComponentKind::DIT:
- return "diffusion";
- case ComponentKind::CONDITIONER:
- return "te";
- case ComponentKind::VAE:
- return "vae";
- }
- return "";
- }
-
- static bool resolve_runtimes(const std::vector<Component>& components,
- const std::vector<Device>& devices,
- std::string& runtime_spec,
- std::vector<Runtime>& runtimes,
- std::string& error) {
- SDBackendAssignment assignment;
- if (!sd_parse_backend_assignment(runtime_spec, &assignment, &error)) {
- return false;
- }
- const size_t main_device = select_main_device(devices);
- const SDBackendModule modules[] = {SDBackendModule::DIFFUSION, SDBackendModule::TE, SDBackendModule::VAE};
- for (const Component& comp : components) {
- std::string name = assignment.get(modules[int(comp.kind)]);
- if (name.empty()) {
- name = main_device == SIZE_MAX ? "cpu" : devices[main_device].name;
- if (comp.params_bytes > 0) {
- append_assignment(runtime_spec, module_key(comp.kind), name);
- }
- }
- Runtime runtime;
- for (const std::string& part : split_string(name, '&')) {
- if (trim(part).empty()) {
- continue;
- }
- const std::string resolved = sd_backend_resolve_name(part);
- if (resolved.empty()) {
- error = "backend '" + part + "' was not found";
- return false;
- }
- if (!runtime.name.empty()) {
- runtime.name += "&";
- }
- runtime.name += resolved;
- for (size_t di = 0; di < devices.size(); ++di) {
- if (devices[di].name == resolved &&
- std::find(runtime.devices.begin(), runtime.devices.end(), di) == runtime.devices.end()) {
- runtime.devices.push_back(di);
- }
- }
- }
- runtimes.push_back(std::move(runtime));
- }
- return true;
- }
-
- static bool derive_component_specs(const std::vector<Component>& components,
- sd::ggml_graph_cut::MaxVramAssignment& budgets,
- std::string& runtime_spec,
- std::string& params_spec,
- const AvailableVRAM& available_vram,
- size_t max_ram_bytes) {
- std::string error;
- if (!budgets.canonicalize_backend_keys(&error)) {
- LOG_ERROR("%s", error.c_str());
- return false;
- }
-
- // Resolve once to ensure dynamic backends are loaded before enumerating devices.
- sd_backend_resolve_name("");
- const auto devices = enumerate_gpu_devices(budgets, !runtime_spec.empty(), available_vram);
- std::vector<Runtime> runtimes;
- if (!runtime_spec.empty() && !resolve_runtimes(components, devices, runtime_spec, runtimes, error)) {
- LOG_ERROR("%s", error.c_str());
- return false;
- }
- const int64_t free_ram = available_ram_bytes();
- int64_t ram_budget = std::max<int64_t>(free_ram - std::max<int64_t>(2048 * MiB, free_ram / 10), 0);
- if (max_ram_bytes)
- ram_budget = static_cast<int64_t>(std::min<uint64_t>(ram_budget, max_ram_bytes));
- const auto plan = compute_plan(components, devices, ram_budget, runtimes);
- params_spec.clear();
- if (!plan.valid) {
- if (devices.empty()) {
- LOG_WARN("auto-fit: no GPU devices; using the default backend");
- } else {
- LOG_WARN("auto-fit: no GPU memory budget available; using CPU");
- runtime_spec = "cpu";
- }
- return true;
- }
-
- print_plan(plan, components, devices, free_ram, ram_budget);
- for (size_t ci = 0; ci < components.size(); ++ci) {
- if (components[ci].params_bytes == 0) {
- continue;
- }
- const char* key = module_key(components[ci].kind);
- if (runtimes.empty()) {
- append_assignment(runtime_spec, key, plan.runtimes[ci].name);
- }
- if (plan.decisions[ci].params_location != ParamsLocation::MAIN_GPU) {
- append_assignment(params_spec, key, params_backend_name(plan.decisions[ci], devices));
- }
- }
-
- // Keep the planner's safety margin when the runner resolves its device limits.
- for (const Device& device : devices) {
- if (device.budget_bytes > 0) {
- budgets.backend_gib[budget_key(device.name)] = (float)(device.budget_bytes / (1024.0 * MiB));
- }
- }
- budgets.resolved_backend_bytes.clear();
-
- LOG_INFO("auto-fit: --backend \"%s\"%s%s%s",
- runtime_spec.empty() ? "(default)" : runtime_spec.c_str(),
- params_spec.empty() ? "" : " --params-backend \"",
- params_spec.c_str(), params_spec.empty() ? "" : "\"");
- return true;
+ for (auto& device : devices)
+ device.budget_bytes = tightest.at(physical_device_key(device.device));
+ return devices;
}
std::string select_default_backend(const sd::ggml_graph_cut::MaxVramAssignment& budgets, const AvailableVRAM& available_vram) {
const auto fallback = sd_backend_resolve_name("");
- const auto devices = enumerate_gpu_devices(budgets, false, available_vram);
+ const auto devices = physical_budgets(budgets, available_vram);
const auto selected = select_main_device(devices);
return selected == SIZE_MAX ? fallback : devices[selected].name;
}
- bool derive_backend_specs(ModelLoader& loader,
- ggml_type override_wtype,
- sd::ggml_graph_cut::MaxVramAssignment& budgets,
- std::string& runtime_spec,
- std::string& params_spec,
- const AvailableVRAM& available_vram,
- size_t max_ram_bytes) {
- return derive_component_specs(estimate_components(loader, override_wtype), budgets, runtime_spec, params_spec,
- available_vram, max_ram_bytes);
+ std::string physical_device_key(ggml_backend_dev_t device) {
+ if (device == nullptr)
+ return {};
+ ggml_backend_dev_props props{};
+ ggml_backend_dev_get_props(device, &props);
+ return props.device_id != nullptr && props.device_id[0] ? std::string("pci:") + props.device_id
+ : std::string("dev:") + ggml_backend_dev_name(device);
}
- bool derive_backend_specs(ModelLoader& loader,
- ggml_type override_wtype,
- sd::ggml_graph_cut::MaxVramAssignment& budgets,
- std::string& runtime_spec,
- std::string& params_spec) {
- return derive_backend_specs(loader, override_wtype, budgets, runtime_spec, params_spec, {});
+ std::vector<DeviceBudget> gpu_device_budgets(const sd::ggml_graph_cut::MaxVramAssignment& budgets, const AvailableVRAM& available_vram) {
+ std::vector<DeviceBudget> result;
+ std::set<std::string> seen;
+ for (const auto& device : physical_budgets(budgets, available_vram)) {
+ if (seen.insert(physical_device_key(device.device)).second)
+ result.push_back({device.device, device.name, static_cast<size_t>(std::max<int64_t>(device.budget_bytes, 0))});
+ }
+ return result;
}
bool prepare_vae_decode_retry_tiling(sd::TilingConfig& tiling_params,
diff --git a/src/core/backend_fit.h b/src/core/backend_fit.h
index 0d45c8d..4ce405c 100644
--- a/src/core/backend_fit.h
+++ b/src/core/backend_fit.h
@@ -3,9 +3,9 @@
#include <functional>
#include <string>
+#include <vector>
#include "core/ggml_graph_cut.h"
-#include "model_loader.h"
#include "stable-diffusion.h"
namespace sd {
@@ -21,19 +21,18 @@ namespace sd::backend_fit {
std::string select_default_backend(const sd::ggml_graph_cut::MaxVramAssignment& budgets, const AvailableVRAM& available_vram = {});
- bool derive_backend_specs(ModelLoader& loader,
- ggml_type override_wtype,
- sd::ggml_graph_cut::MaxVramAssignment& budgets,
- std::string& runtime_spec,
- std::string& params_spec);
-
- bool derive_backend_specs(ModelLoader& loader,
- ggml_type override_wtype,
- sd::ggml_graph_cut::MaxVramAssignment& budgets,
- std::string& runtime_spec,
- std::string& params_spec,
- const AvailableVRAM& available_vram,
- size_t max_ram_bytes = 0);
+ struct DeviceBudget {
+ ggml_backend_dev_t device = nullptr;
+ std::string name;
+ size_t bytes = 0;
+ };
+
+ // Identifies the physical GPU; backends exposing the same card share it.
+ std::string physical_device_key(ggml_backend_dev_t device);
+
+ // Weight and compute budget of each physical GPU after --max-vram and reclaimable weights.
+ // A card exposed by several backends is listed once, under its first device.
+ std::vector<DeviceBudget> gpu_device_budgets(const sd::ggml_graph_cut::MaxVramAssignment& budgets, const AvailableVRAM& available_vram = {});
bool prepare_vae_decode_retry_tiling(sd::TilingConfig& tiling_params,
bool prefer_temporal_tiling,
diff --git a/src/core/compute_workspace.cpp b/src/core/compute_workspace.cpp
index d836341..4896a41 100644
--- a/src/core/compute_workspace.cpp
+++ b/src/core/compute_workspace.cpp
@@ -325,8 +325,12 @@ namespace sd {
}
size_t ComputeWorkspace::bytes(ggml_backend_t backend) const {
- if (scheduler_ != nullptr) {
- return ggml_backend_sched_get_buffer_size(scheduler_, backend);
+ if (scheduler_ == nullptr)
+ return 0;
+ // The scheduler asserts on a backend it does not hold, such as another session's device.
+ for (int i = 0; i < ggml_backend_sched_get_n_backends(scheduler_); ++i) {
+ if (ggml_backend_sched_get_backend(scheduler_, i) == backend)
+ return ggml_backend_sched_get_buffer_size(scheduler_, backend);
}
return 0;
}
diff --git a/src/core/execution_engine.cpp b/src/core/execution_engine.cpp
index 0e7ce24..4b25a7f 100644
--- a/src/core/execution_engine.cpp
+++ b/src/core/execution_engine.cpp
@@ -14,6 +14,10 @@
#include "core/tensor_ggml.hpp"
#include "core/util.h"
+sd::weights::CapacityProvider& DeviceResidencyManager::capacity_provider() {
+ return *execution_engine();
+}
+
std::shared_ptr<sd::ExecutionEngine> DeviceResidencyManager::execution_engine() {
if (execution_engine_ == nullptr) {
execution_engine_ = std::make_shared<sd::ExecutionEngine>(this);
@@ -434,6 +438,7 @@ namespace sd {
}
requests.push_back({size.backend, session_.owner_id(), pending,
retained, limit});
+ requests.back().recoverable = task_.capacity_failure_recoverable;
}
return requests;
}
@@ -446,7 +451,9 @@ namespace sd {
return params.empty();
}
for (const auto& request : requests) {
- if (!manager->fits_compute_backend_capacity(request, params, check)) {
+ const bool fits = check == DeviceMemoryCheck::Reclaimable ? engine_.fits_after_reclaim(*manager, request, params)
+ : manager->fits_compute_backend_capacity(request, params, check);
+ if (!fits) {
return false;
}
}
@@ -607,7 +614,10 @@ 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);
- LOG_ERROR("%s", message.c_str());
+ if (task_.capacity_failure_recoverable && !device_memory_error_.empty())
+ LOG_INFO("%s", message.c_str());
+ else
+ LOG_ERROR("%s", message.c_str());
if (!device_memory_error_.empty()) {
device_memory_error_ = message + ": " + device_memory_error_;
}
@@ -661,7 +671,20 @@ namespace sd {
auto ensure_capacity = [&]() {
sync_runtime_residency();
auto requests = memory_requests(measurement.buffers, new_cache_bytes);
- if (fits(requests, weights.params(index), DeviceMemoryCheck::TrimBufferCache)) {
+ if (manager != nullptr) {
+ for (const auto& request : requests) {
+ engine_.trim_buffer_pool(*manager, request, weights.params(index));
+ }
+ }
+ if (fits(requests, weights.params(index), DeviceMemoryCheck::Inspect)) {
+ return true;
+ }
+ // 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 (session_.workspace_.release_excess(measurement)) {
@@ -899,7 +922,10 @@ namespace sd {
if (prefetch_buffer != nullptr && !prefetch_buffer->buffer) {
prefetch_buffer->buffer.reset(sd_backend_try_alloc_buffer_from_cache(prefetch_buffer->type, prefetch_buffer->bytes));
}
- auto capacity = [&]() { return manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::TrimBufferCache); };
+ auto capacity = [&]() {
+ trim_buffer_pool(manager, request, required_params);
+ return manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect);
+ };
const auto initial = capacity();
if (!initial.valid) {
return false;
@@ -907,6 +933,16 @@ namespace sd {
if (initial.fits()) {
return true;
}
+ // Weight copies go first: a copy demoted once is cheap to drop later, while compute
+ // buffers are reused by every graph.
+ const auto candidates = manager.plan_reclaim(request, required_params, preferred_eviction_order, protected_params);
+ auto protected_weights = protected_params;
+ 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;
+ }
+ }
for (auto& entry : sessions_) {
auto& session = *entry.second;
if (session.owner_id() != request.owner_id && !session.executing_ && session.workspace_.release()) {
@@ -916,52 +952,6 @@ namespace sd {
}
}
}
- auto protected_weights = protected_params;
- protected_weights.insert(protected_weights.end(), required_params.begin(), required_params.end());
- auto candidates = manager.evictable_compute_backend_blocks(request.compute_backend, protected_weights);
- std::unordered_map<const ggml_tensor*, size_t> preferred_positions;
- for (size_t index = 0; index < preferred_eviction_order.size(); ++index) {
- for (auto* tensor : preferred_eviction_order[index]) {
- auto* weight = manager.resolve_param_tensor(tensor);
- preferred_positions.emplace(weight != nullptr ? weight : tensor, index);
- }
- }
- auto preferred_position = [&](const WeightResidencyBlock& block) {
- size_t position = 0;
- // A shared allocation follows the last of its members in the eviction order.
- for (auto* tensor : block.tensors) {
- const auto found = preferred_positions.find(tensor);
- if (found == preferred_positions.end()) {
- return SIZE_MAX;
- }
- position = std::max(position, found->second);
- }
- return position;
- };
- std::stable_sort(candidates.begin(), candidates.end(), [&](const auto& lhs, const auto& rhs) {
- if (lhs.next_use != rhs.next_use)
- return lhs.next_use > rhs.next_use;
- const auto left = preferred_position(lhs), right = preferred_position(rhs);
- if (manager.retains_idle_weights() && (left == SIZE_MAX) != (right == SIZE_MAX))
- return left == SIZE_MAX;
- if (lhs.requires_demotion != rhs.requires_demotion) {
- return !lhs.requires_demotion;
- }
- if (!lhs.requires_demotion) {
- if (left != right) {
- return left < right;
- }
- if (left != SIZE_MAX) {
- return false;
- }
- }
- return lhs.last_use_epoch < rhs.last_use_epoch;
- });
- for (const auto& block : candidates) {
- if (manager.evict_compute_backend_block(block, prefetch_buffer) && capacity().fits(true)) {
- return true;
- }
- }
auto available = capacity();
if (available.fits(true)) {
return true;
@@ -982,7 +972,11 @@ namespace sd {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while (std::chrono::steady_clock::now() < deadline);
}
- available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect, true);
+ if (request.quiet) {
+ return false;
+ }
+ available = manager.inspect_compute_backend_capacity(request, required_params, DeviceMemoryCheck::Inspect,
+ !request.recoverable);
const auto device_bytes = available.available_device_bytes == SIZE_MAX
? std::string("unknown")
: sd_format("%.2f MB", available.available_device_bytes / (1024.0 * 1024.0));
@@ -993,13 +987,82 @@ namespace sd {
ggml_backend_name(request.compute_backend),
available.required_device_bytes / (1024.0 * 1024.0),
available.required_budget_bytes / (1024.0 * 1024.0), device_bytes.c_str(), budget_bytes.c_str());
- LOG_WARN("%s", message.c_str());
+ if (request.recoverable)
+ LOG_INFO("%s", message.c_str());
+ else
+ LOG_WARN("%s", message.c_str());
if (device_memory_error != nullptr && available.valid) {
*device_memory_error = std::move(message);
}
return false;
}
+ void ExecutionEngine::trim_buffer_pool(const DeviceResidencyManager& manager,
+ const DeviceMemoryRequest& request,
+ const std::vector<ggml_tensor*>& params) const {
+ if (request.compute_backend == nullptr || sd_backend_is_cpu(request.compute_backend))
+ return;
+ const auto capacity = manager.inspect_compute_backend_capacity(request, params, DeviceMemoryCheck::Inspect);
+ auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; };
+ for (const auto& pool : capacity.pools) {
+ if (!pool.accounted) {
+ // An older backend may expose reuse without exposing the retained bytes.
+ if (pool.limit > 0)
+ sd_backend_set_buffer_cache_enabled(pool.backend, false);
+ continue;
+ }
+ const size_t in_use = add(pool.resident, request.runtime_resident_bytes);
+ const size_t peak = add(pool.resident, capacity.required_budget_bytes);
+ // If trimming alone cannot admit a prefetch, an evicted weight buffer may satisfy it without growing the pool.
+ const bool wait_for_eviction = request.prefetch_buffer && !request.prefetch_buffer->buffer && pool.limit > 0 &&
+ peak > pool.limit && add(in_use, pool.cached_bytes) <= pool.limit;
+ size_t cache_limit = pool.limit == 0 ? SIZE_MAX : pool.limit - std::min(pool.limit, wait_for_eviction ? in_use : peak);
+ if (!wait_for_eviction && pool.total_bytes > 0 && pool.free_bytes < capacity.required_device_bytes) {
+ const size_t shortfall = capacity.required_device_bytes - pool.free_bytes;
+ cache_limit = std::min(cache_limit, pool.cached_bytes - std::min(pool.cached_bytes, shortfall));
+ }
+ sd_backend_set_buffer_cache_limit(pool.device, cache_limit);
+ if (pool.cached_bytes <= cache_limit)
+ continue;
+ size_t free_bytes = 0, total_bytes = 0, cached_bytes = 0;
+ sd_backend_get_buffer_cache_memory(pool.device, free_bytes, total_bytes, cached_bytes);
+ // Virtual CUDA devices may regain only a fraction of the bytes released.
+ if (cached_bytes > 0 && free_bytes < capacity.required_device_bytes) {
+ sd_backend_set_buffer_cache_limit(pool.device, 0);
+ sd_backend_get_buffer_cache_memory(pool.device, free_bytes, total_bytes, cached_bytes);
+ }
+ LOG_DEBUG("execution engine trimmed the idle buffer pool on %s from %.2f MiB to %.2f MiB",
+ ggml_backend_name(pool.backend), pool.cached_bytes / (1024.0 * 1024.0), cached_bytes / (1024.0 * 1024.0));
+ }
+ }
+
+ size_t ExecutionEngine::idle_workspace_bytes(uintptr_t owner_id, ggml_backend_t backend) const {
+ size_t bytes = 0;
+ for (const auto& entry : sessions_) {
+ const auto& session = *entry.second;
+ if (session.owner_id() == owner_id || session.executing_ || session.workspace_.active())
+ continue;
+ const size_t size = session.workspace_.bytes(backend);
+ bytes = size > SIZE_MAX - bytes ? SIZE_MAX : bytes + size;
+ }
+ return bytes;
+ }
+
+ bool ExecutionEngine::fits_after_reclaim(const DeviceResidencyManager& manager,
+ const DeviceMemoryRequest& request,
+ const std::vector<ggml_tensor*>& params) const {
+ if (manager.fits_compute_backend_capacity(request, params, DeviceMemoryCheck::Inspect))
+ return true;
+ auto capacity = manager.inspect_compute_backend_capacity(request, params, DeviceMemoryCheck::Reclaimable);
+ // Each device gains only the idle workspaces it holds itself.
+ std::vector<ggml_backend_t> backends;
+ for (const auto& device : capacity.devices)
+ backends.push_back(device.backend);
+ for (auto backend : backends)
+ capacity.add_reclaimable(backend, idle_workspace_bytes(request.owner_id, backend));
+ return capacity.fits();
+ }
+
void ExecutionEngine::clear_cache(ExecutionSession& session) {
session.cache_.clear();
sync_residency(session);
diff --git a/src/core/execution_engine.h b/src/core/execution_engine.h
index 9fb8e7b..18b5263 100644
--- a/src/core/execution_engine.h
+++ b/src/core/execution_engine.h
@@ -16,6 +16,7 @@
#include "core/runner_cache.h"
#include "core/tensor.hpp"
#include "device_residency_manager.h"
+#include "weights/capacity.h"
namespace sd {
struct ComputeTask {
@@ -27,6 +28,8 @@ namespace sd {
std::vector<std::pair<ggml_tensor*, std::string>> debug_tensors;
int n_threads = 1;
bool no_return = false;
+ // The caller retries capacity failures with less work, so they are not logged as errors.
+ bool capacity_failure_recoverable = false;
std::function<bool()> read_outputs;
};
@@ -79,7 +82,7 @@ namespace sd {
void set_runtime_backends(const std::vector<ggml_backend_t>& backends);
};
- class ExecutionEngine {
+ class ExecutionEngine final : public weights::CapacityProvider {
friend class GraphExecution;
std::map<uintptr_t, std::unique_ptr<ExecutionSession>> sessions_;
@@ -103,8 +106,26 @@ namespace sd {
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,
+ 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);
+ }
// Graphs, input data and output callbacks remain borrowed until execute returns.
ComputeResult execute(ExecutionSession& session, const ComputeTask& task);
+ // Returns idle buffer pool memory the request needs on each of its devices.
+ void trim_buffer_pool(const DeviceResidencyManager& manager,
+ const DeviceMemoryRequest& request,
+ const std::vector<ggml_tensor*>& params) const;
+ // Workspace bytes ensure_capacity() can release from other idle sessions on the backend.
+ size_t idle_workspace_bytes(uintptr_t owner_id, ggml_backend_t backend) const;
+ // Whether ensure_capacity() can make the request fit: reclaimable weights plus idle workspaces.
+ bool fits_after_reclaim(const DeviceResidencyManager& manager,
+ const DeviceMemoryRequest& request,
+ const std::vector<ggml_tensor*>& params) const;
};
}
diff --git a/src/core/ggml_runner.cpp b/src/core/ggml_runner.cpp
index 6ffea31..b03d662 100644
--- a/src/core/ggml_runner.cpp
+++ b/src/core/ggml_runner.cpp
@@ -308,19 +308,20 @@ std::optional<sd::Tensor<float>> GGMLRunner::compute(get_graph_cb_t get_graph,
params_tensor_set_dirty_ = true;
rebuild_params_tensor_set();
sd::ComputeTask task;
- task.description = get_desc();
- task.graph = graph;
- task.output = no_return ? nullptr : ggml_get_tensor(compute_ctx, final_result_name.c_str());
- task.weights = collect_used_param_tensors(graph);
- task.inputs = backend_tensor_data_map;
- task.debug_tensors = debug_tensors;
- task.n_threads = n_threads;
- task.no_return = no_return;
- task.read_outputs = read_outputs;
- auto result = execution_engine_->execute(execution_session_, task);
- last_compute_status_ = result.status;
- device_memory_error_ = std::move(result.device_memory_error);
- success = result.status == GGML_STATUS_SUCCESS;
+ task.description = get_desc();
+ task.graph = graph;
+ task.output = no_return ? nullptr : ggml_get_tensor(compute_ctx, final_result_name.c_str());
+ task.weights = collect_used_param_tensors(graph);
+ task.inputs = backend_tensor_data_map;
+ task.debug_tensors = debug_tensors;
+ task.n_threads = n_threads;
+ task.no_return = no_return;
+ task.read_outputs = read_outputs;
+ task.capacity_failure_recoverable = capacity_failure_recoverable;
+ auto result = execution_engine_->execute(execution_session_, task);
+ last_compute_status_ = result.status;
+ device_memory_error_ = std::move(result.device_memory_error);
+ 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 6cd8032..bd94952 100644
--- a/src/core/ggml_runner.h
+++ b/src/core/ggml_runner.h
@@ -168,16 +168,18 @@ protected:
std::vector<std::pair<ggml_tensor*, std::string>> debug_tensors;
const std::string final_result_name = "ggml_runner_final_result_tensor";
- bool flash_attn_enabled = false;
- bool sage_attn_enabled = false;
- bool requantize_to_i8 = false;
- float linear_scale = 0.f;
- float conv_scale = 0.f;
- float attn_scale = 0.f;
- bool conv2d_direct_enabled = false;
- bool conv3d_direct_enabled = false;
- bool circular_x_enabled = false;
- bool circular_y_enabled = false;
+ bool flash_attn_enabled = false;
+ bool sage_attn_enabled = false;
+ // The caller retries capacity failures with less work, so they are not logged as errors.
+ bool capacity_failure_recoverable = false;
+ bool requantize_to_i8 = false;
+ float linear_scale = 0.f;
+ float conv_scale = 0.f;
+ float attn_scale = 0.f;
+ bool conv2d_direct_enabled = false;
+ bool conv3d_direct_enabled = false;
+ bool circular_x_enabled = false;
+ bool circular_y_enabled = false;
std::unordered_set<const ggml_tensor*> params_tensor_set_;
@@ -307,6 +309,10 @@ public:
const std::string& device_memory_error() const { return device_memory_error_; }
void clear_device_memory_error() { device_memory_error_.clear(); }
+ void set_capacity_failure_recoverable(bool recoverable) {
+ capacity_failure_recoverable = recoverable;
+ }
+
void set_flash_attention_enabled(bool enabled) {
flash_attn_enabled = enabled;
}
diff --git a/src/device_residency_manager.h b/src/device_residency_manager.h
index 82fe7cc..ba223fb 100644
--- a/src/device_residency_manager.h
+++ b/src/device_residency_manager.h
@@ -14,6 +14,9 @@ struct ggml_tensor;
namespace sd {
class ExecutionEngine;
}
+namespace sd::weights {
+ class CapacityProvider;
+}
enum class WeightPrefetchResult {
Scheduled,
@@ -43,6 +46,14 @@ struct DeviceMemoryRequest {
// Exact-size buffer already checked out of the pool for this request.
size_t reused_buffer_bytes = 0;
PrefetchBuffer* prefetch_buffer = nullptr;
+ // The caller has another fallback; a failure is not reported.
+ bool quiet = false;
+ // The caller retries a failure with less work: it is still reported, but not logged as a warning.
+ bool recoverable = false;
+ // Making room for a demotion releases victims instead of copying them further.
+ bool release_only = false;
+ // Protected weights a reclaim may release because the caller loads them again; not counted as missing.
+ const std::vector<ggml_tensor*>* reloadable_params = nullptr;
// Runtime buffers only; the manager accounts for weights separately.
size_t runtime_peak_bytes() const {
@@ -52,14 +63,65 @@ struct DeviceMemoryRequest {
}
};
+// Idle buffer pool of one device as a capacity check saw it.
+struct BufferPoolState {
+ ggml_backend_dev_t device = nullptr;
+ ggml_backend_t backend = nullptr;
+ // The backend reports the bytes its pool retains.
+ bool accounted = false;
+ size_t free_bytes = 0;
+ size_t total_bytes = 0;
+ size_t cached_bytes = 0;
+ // Budget limit; 0 means none.
+ size_t limit = 0;
+ // Weights and other runtime allocations counted against the limit.
+ size_t resident = 0;
+};
+
+// Headroom of one device; a request fits when every participating device fits.
+struct DeviceHeadroom {
+ ggml_backend_t backend = nullptr;
+ size_t available_device = SIZE_MAX;
+ size_t available_budget = SIZE_MAX;
+ size_t overcommitted = 0;
+};
+
struct DeviceMemoryCapacity {
size_t required_device_bytes = 0;
size_t required_budget_bytes = 0;
size_t available_device_bytes = SIZE_MAX;
size_t available_budget_bytes = SIZE_MAX;
bool requires_reclamation = false;
- bool valid = true;
- bool wrapped_device_report = false;
+ // Bytes committed above the budget limit; requires_reclamation while nonzero.
+ size_t overcommitted_bytes = 0;
+ bool valid = true;
+ bool wrapped_device_report = false;
+ std::vector<BufferPoolState> pools;
+ std::vector<DeviceHeadroom> devices;
+
+ // Counts runtime memory the caller can release on one device, e.g. idle workspaces of other
+ // sessions, then recomputes the totals from every device.
+ void add_reclaimable(ggml_backend_t backend, size_t bytes) {
+ auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; };
+ for (auto& device : devices) {
+ if (device.backend != backend)
+ continue;
+ const size_t covered = bytes < device.overcommitted ? bytes : device.overcommitted;
+ if (device.available_device != SIZE_MAX)
+ device.available_device = add(device.available_device, bytes);
+ if (device.available_budget != SIZE_MAX)
+ device.available_budget = add(device.available_budget, bytes - covered);
+ device.overcommitted -= covered;
+ }
+ available_device_bytes = available_budget_bytes = SIZE_MAX;
+ overcommitted_bytes = 0;
+ for (const auto& device : devices) {
+ available_device_bytes = available_device_bytes < device.available_device ? available_device_bytes : device.available_device;
+ available_budget_bytes = available_budget_bytes < device.available_budget ? available_budget_bytes : device.available_budget;
+ overcommitted_bytes = overcommitted_bytes > device.overcommitted ? overcommitted_bytes : device.overcommitted;
+ }
+ requires_reclamation = overcommitted_bytes != 0;
+ }
bool fits(bool after_reclamation = false) const {
return valid && !requires_reclamation &&
@@ -72,17 +134,28 @@ struct DeviceMemoryCapacity {
enum class DeviceMemoryCheck {
Inspect,
Reclaimable,
- TrimBufferCache,
};
+enum class ReclaimAction {
+ // Free a copy that has another copy or the model file below it.
+ Drop,
+ // Copy to the next residency location, then free; releases when no location has room.
+ Move,
+ // Free the only copy above the model file.
+ Release,
+};
+
+// One reclaim action. Capacity checks and execution use the same actions.
struct WeightResidencyBlock {
ggml_backend_buffer_t buffer = nullptr;
ggml_backend_t backend = nullptr;
std::vector<ggml_tensor*> tensors;
- size_t bytes = 0;
- uint64_t last_use_epoch = 0;
- size_t next_use = 0;
- bool requires_demotion = false;
+ size_t bytes = 0;
+ ReclaimAction action = ReclaimAction::Drop;
+ // Weights of the current request that must load again after this action.
+ size_t restage_bytes = 0;
+
+ size_t net_bytes() const { return bytes - (restage_bytes < bytes ? restage_bytes : bytes); }
};
struct DeviceResidencyManager {
@@ -93,10 +166,11 @@ public:
virtual ~DeviceResidencyManager() = default;
virtual std::shared_ptr<sd::ExecutionEngine> execution_engine();
+ // Where weight allocations reserve device memory: the runtime that owns this manager.
+ sd::weights::CapacityProvider& capacity_provider();
virtual bool segmented_compute_enabled() const = 0;
virtual bool prefetch_enabled() const = 0;
- virtual bool retains_idle_weights() const { return false; }
virtual size_t context_vram_limit(ggml_backend_t) const { return 0; }
// Device bytes consume Windows commit without consuming physical host RAM.
virtual bool ensure_host_memory(size_t, const std::vector<ggml_tensor*>&, size_t = 0) { return true; }
@@ -111,7 +185,8 @@ public:
virtual ggml_tensor* resolve_param_tensor(ggml_tensor* tensor) const { return nullptr; }
virtual bool prepare_params(const std::vector<ggml_tensor*>& tensors) = 0;
virtual void release_compute_backend_params(const std::vector<ggml_tensor*>& tensors) = 0;
- virtual void evict_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;
virtual WeightResidencyInfo inspect_compute_backend_params(
const std::vector<ggml_tensor*>& tensors) const = 0;
virtual void update_runtime_residency(uintptr_t owner_id,
@@ -132,10 +207,14 @@ public:
result.valid = false;
return result;
}
- virtual std::vector<WeightResidencyBlock> evictable_compute_backend_blocks(
- ggml_backend_t backend,
+ // Reclaim actions for the request in execution order.
+ virtual std::vector<WeightResidencyBlock> plan_reclaim(
+ 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) const { return {}; }
- virtual bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer = nullptr) { return false; }
+ // protected_params: weights of the request the action makes room for; nested reclaim keeps them.
+ virtual bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer = nullptr, const std::vector<ggml_tensor*>* protected_params = nullptr) { return false; }
virtual WeightPrefetchResult prefetch_params(
uintptr_t owner_id,
const std::vector<ggml_tensor*>& tensors) = 0;
diff --git a/src/dgl/bindings/component_loader.cpp b/src/dgl/bindings/component_loader.cpp
index ca7fceb..6a37efc 100644
--- a/src/dgl/bindings/component_loader.cpp
+++ b/src/dgl/bindings/component_loader.cpp
@@ -105,10 +105,10 @@ namespace sd::dgl {
read_model_params(args),
};
PreparedResource prepared;
- prepared.key = normalized_model_params(params.model, prepared);
- params.model.weights_override = file_key(get_string(args, "weights_override"), prepared.revision);
+ prepared.key = normalized_model_params(params.model, prepared);
+ params.model.weights_override = file_key(get_string(args, "weights_override"), prepared.revision);
prepared.key["weights_override"] = params.model.weights_override;
- prepared.load = [params = std::move(params)](ResourceLoadRequest& request) mutable {
+ prepared.load = [params = std::move(params)](ResourceLoadRequest& request) mutable {
const auto path = params.model.path;
auto model = load_model<models::DiT>(request, std::move(params), path);
return Value::object(std::make_shared<models::DiffusionModel>(models::DiffusionModel{std::move(model)}));
diff --git a/src/dgl/context.cpp b/src/dgl/context.cpp
index 80e43e6..ac22bd9 100644
--- a/src/dgl/context.cpp
+++ b/src/dgl/context.cpp
@@ -24,7 +24,6 @@ namespace sd::dgl {
model_execution_.backend_probes = std::make_shared<BackendProbeCache>();
model_execution_.family_probes = std::make_shared<models::FamilyProbeCache>();
model_execution_.defer_initialization = true;
- models->set_retain_weights(true);
models->set_idle_resource_eviction([this] { return evict_idle_resource(); });
}
diff --git a/src/dgl/dgl.cpp b/src/dgl/dgl.cpp
index 1acd994..fec039e 100644
--- a/src/dgl/dgl.cpp
+++ b/src/dgl/dgl.cpp
@@ -148,14 +148,6 @@ bool sd_dgl_ctx_set(sd_dgl_ctx_t* ctx, const char* key, const char* value) {
}) == SD_STATUS_OK;
}
-sd_status_t sd_dgl_ctx_release_staging(sd_dgl_ctx_t* ctx) {
- return api_call([&] {
- auto lock = lock_idle(ctx);
- ctx->models->release_idle_gpu_staging();
- clear_backend_buffer_caches(*ctx);
- });
-}
-
sd_status_t sd_dgl_ctx_unload_models(sd_dgl_ctx_t* ctx) {
return api_call([&] {
auto lock = lock_idle(ctx);
diff --git a/src/dgl/executor.cpp b/src/dgl/executor.cpp
index 920f776..6fb51e3 100644
--- a/src/dgl/executor.cpp
+++ b/src/dgl/executor.cpp
@@ -226,7 +226,7 @@ namespace sd::dgl {
if (operation.resource())
failure = SD_STATUS_LOAD_FAILED;
state_.events.check_cancelled();
- Value value = operation.resource() ? (state_.plan ? state_.plan->load_resource(*bound.operation, args) : state_.context.load(*bound.operation, args, true))
+ Value value = operation.resource() ? (state_.plan ? state_.plan->load_resource(expr.get(), *bound.operation, args) : state_.context.load(*bound.operation, args, true))
: operation.execute(args, state_);
if (operation.resource()) {
if (state_.plan)
diff --git a/src/dgl/models/model_runtime.cpp b/src/dgl/models/model_runtime.cpp
index 22ff2e8..fa4225a 100644
--- a/src/dgl/models/model_runtime.cpp
+++ b/src/dgl/models/model_runtime.cpp
@@ -308,7 +308,7 @@ namespace sd::dgl::models {
model->set_runtime_backends(module_backends);
model->set_graph_cut_layer_split_enabled(true);
- model_.model_weights->set_layer_split(true);
+ model_.model_weights->set_layer_split(true, module_backends);
const bool params_follow_runtime = backend_manager.params_backend_follows_runtime(module) ||
backend_manager.params_backend_is_disk(module);
ggml_backend_t initial_params_backend = params_follow_runtime ? module_backends[0] : params_backend_for();
diff --git a/src/dgl/run_plan.cpp b/src/dgl/run_plan.cpp
index 48e3edf..4df8dde 100644
--- a/src/dgl/run_plan.cpp
+++ b/src/dgl/run_plan.cpp
@@ -5,6 +5,7 @@
#include "context.h"
#include "core/backend_fit.h"
+#include "core/ggml_extend_backend.h"
#include "core/util.h"
#include "executor.h"
#include "model_value.h"
@@ -16,14 +17,30 @@ namespace sd::dgl {
return b > SIZE_MAX - a ? SIZE_MAX : a + b;
}
+ static int priority(Kind kind) {
+ switch (kind) {
+ case Kind::Denoiser:
+ return 0;
+ case Kind::TextEncoder:
+ return 1;
+ case Kind::VAE:
+ return 2;
+ default:
+ return 3;
+ }
+ }
+
+ static bool empty_argument(const Values& args, const char* name) {
+ const auto found = args.find(name);
+ return found != args.end() && trim(found->second.scalar.template get<std::string>()).empty();
+ }
+
RunPlan::RunPlan(const Graph& graph, RunState& state)
: graph_(graph), state_(state), enabled_(state.context.auto_fit()), vae_preview_(state.events.preview_callback() && (state.events.callbacks().mode == PREVIEW_VAE || state.events.callbacks().mode == PREVIEW_TAE) && (state.events.callbacks().noisy || state.events.callbacks().denoised)) {
if (graph.resources.empty())
return;
if (std::any_of(graph.resources.begin(), graph.resources.end(), [](const auto& call) {
- const auto backend = call.arguments.find("backend");
- return is_model_kind(call.operation->second.output.type.kind) && backend != call.arguments.end() &&
- trim(backend->second.scalar.template get<std::string>()).empty();
+ return is_model_kind(call.operation->second.output.type.kind) && empty_argument(call.arguments, "backend");
})) {
SDBackendManager backends(state.context.backends);
default_backend_ = enabled_ ? sd::backend_fit::select_default_backend(state.context.models->max_vram(), [&](auto device, auto free, auto total) {
@@ -39,7 +56,7 @@ namespace sd::dgl {
continue;
try {
auto args = call.arguments;
- auto value = load_resource(*call.operation, args);
+ auto value = load_resource(call.expression, *call.operation, args);
add_model(call, value);
prepared_.emplace(call.expression, std::move(value));
} catch (const std::bad_alloc&) {
@@ -54,29 +71,19 @@ namespace sd::dgl {
std::to_string(call.expression->column) + ": " + error.what());
}
}
- for (const auto& entry : models_)
- for (auto backend : entry.memory.compute_backends) {
- if (budgets_.count(backend) || sd_backend_is_cpu(backend))
- continue;
- size_t free = 0, total = 0;
- ggml_backend_dev_memory(ggml_backend_get_device(backend), &free, &total);
- auto available = state.context.models->available_vram_for_fit(backend, free, total);
- if (!state.context.models->max_vram_bytes(backend))
- available -= std::min(available, 512 * MiB);
- budgets_[backend] = available;
- }
- const auto ram = state.context.models->available_ram_for_fit();
- ram_budget_ = ram.weights;
- host_budget_ = ram.total;
+ update_budgets();
place_models();
if (!models_.empty()) {
- LOG_VERBOSE("auto-fit plan: %zu models, %zu phases", models_.size(), graph.phases.size());
- for (const auto& [backend, bytes] : budgets_)
- LOG_VERBOSE(" %s: available weight/compute budget %.2f MiB", ggml_backend_name(backend), bytes / double(MiB));
- for (const auto& entry : models_)
- LOG_VERBOSE(" %s: %.2f MiB params -> %s", entry.name.c_str(), entry.memory.params_bytes / double(MiB),
- entry.memory.mode == ModelManager::ResidencyMode::Disk ? "disk" : entry.memory.params_backend ? ggml_backend_name(entry.memory.params_backend)
- : "(none)");
+ LOG_VERBOSE("auto-fit plan: %zu models, %zu phases, %.2f MiB RAM for weights", models_.size(), graph.phases.size(), ram_budget_ / double(MiB));
+ for (const auto& [device, bytes] : budgets_)
+ LOG_VERBOSE(" %s: available weight/compute budget %.2f MiB", device_names_.at(device).c_str(), bytes / double(MiB));
+ for (const auto& entry : models_) {
+ const auto& memory = entry.memory;
+ const auto compute = memory.compute_backends.empty() ? "(none)" : ggml_backend_name(memory.compute_backends.front());
+ const auto params = memory.mode == ModelManager::ResidencyMode::Disk ? "disk" : memory.params_backend ? ggml_backend_name(memory.params_backend)
+ : "(none)";
+ LOG_VERBOSE(" %s: %.2f MiB params, compute %s, params %s", entry.name.c_str(), memory.params_bytes / double(MiB), compute, params);
+ }
for (const auto& phase : graph.phases) {
std::string names;
std::set<size_t> seen;
@@ -98,19 +105,26 @@ namespace sd::dgl {
state_.context.models->set_weight_use_priorities({});
}
- Value RunPlan::load_resource(const Registry::Entry& operation, Values& args) {
+ Value RunPlan::load_resource(const Expr* expression, const Registry::Entry& operation, Values& args) {
auto backend = args.find("backend");
- if (!default_backend_.empty() && is_model_kind(operation.second.output.type.kind) && backend != args.end() &&
- trim(backend->second.scalar.get<std::string>()).empty())
- backend->second = Value::literal(default_backend_);
+ if (is_model_kind(operation.second.output.type.kind) && backend != args.end() &&
+ trim(backend->second.scalar.get<std::string>()).empty()) {
+ auto name = default_backend_;
+ if (const auto origin = origins_.find(expression); origin != origins_.end() && !models_[origin->second].backend.empty())
+ name = models_[origin->second].backend;
+ if (!name.empty())
+ backend->second = Value::literal(name);
+ }
return state_.context.load(operation, args, true);
}
size_t RunPlan::add_model(const Graph::ResourceCall& call, const Value& value) {
if (!is_model_kind(value.type().kind) || !value.model_source)
return SIZE_MAX;
- const auto& key = value.model_source->key;
- auto found = identities_.find(key);
+ const auto& key = value.model_source->key;
+ const bool compute_automatic = empty_argument(call.arguments, "backend");
+ const auto identity = std::make_pair(key, compute_automatic);
+ const auto found = identities_.find(identity);
size_t index;
if (found == identities_.end()) {
auto& model = model_from_value(value);
@@ -120,8 +134,8 @@ namespace sd::dgl {
const auto kind = value.type().kind;
const auto reserve = kind == Kind::Denoiser || kind == Kind::TextEncoder ? 2048 * MiB : 1024 * MiB;
index = models_.size();
- models_.push_back({key, call.expression->name, kind, std::move(memory), reserve, automatic});
- identities_[key] = index;
+ models_.push_back({key, call.expression->name, kind, std::move(memory), reserve, automatic, compute_automatic});
+ identities_[identity] = index;
} else
index = found->second;
origins_[call.expression] = index;
@@ -132,96 +146,178 @@ namespace sd::dgl {
return !use.preview || vae_preview_;
}
- void RunPlan::place_models() {
- std::vector<std::pair<size_t, Value>> order;
- for (size_t i = 0; i < models_.size(); ++i) {
- auto& entry = models_[i];
- entry.placed = true;
- auto cached = state_.context.resources.find({entry.key, {}});
- if (cached == state_.context.resources.end())
- continue;
- if (auto value = cached->second.value.lock()) {
- entry.placed = !entry.automatic;
- order.emplace_back(i, std::move(*value));
- }
- }
- std::stable_sort(order.begin(), order.end(), [&](const auto& a, const auto& b) {
- const auto& left = models_[a.first];
- const auto& right = models_[b.first];
- if ((left.kind == Kind::Denoiser) != (right.kind == Kind::Denoiser))
- return left.kind == Kind::Denoiser;
- return left.memory.params_bytes > right.memory.params_bytes;
- });
- for (const auto& [index, value] : order) {
- place(index, model_from_value(value));
- models_[index].placed = true;
+ void RunPlan::update_budgets() {
+ SDBackendManager backends(state_.context.backends);
+ budgets_.clear();
+ device_names_.clear();
+ const auto& models = *state_.context.models;
+ for (const auto& budget : sd::backend_fit::gpu_device_budgets(models.max_vram(), [&](auto device, auto free, auto total) {
+ return models.available_vram_for_fit(backends.existing_backend(device), free, total);
+ })) {
+ const auto key = sd::backend_fit::physical_device_key(budget.device);
+ budgets_[key] = budget.bytes;
+ device_names_[key] = budget.name;
}
+ ram_budget_ = models.available_ram_for_fit().weights;
}
- size_t RunPlan::peak_bytes(ggml_backend_t backend, size_t candidate, bool workspace) const {
- size_t peak = 0;
- for (size_t phase_index = current_; phase_index < graph_.phases.size(); ++phase_index) {
- const auto& phase = graph_.phases[phase_index];
- std::set<size_t> active_models;
- for (const auto& use : phase.resources) {
- auto found = origins_.find(use.resource);
- if (active(use) && found != origins_.end())
- active_models.insert(found->second);
- }
- if (!active_models.count(candidate))
- continue;
- size_t bytes = 0;
- for (auto index : active_models) {
- const auto& entry = models_[index];
- const auto& memory = entry.memory;
- const bool compute = std::find(memory.compute_backends.begin(), memory.compute_backends.end(), backend) != memory.compute_backends.end();
- // Unplaced automatic models reserve staging space before competing for parameter storage.
- const bool placed = index == candidate || entry.placed || !entry.automatic;
- if (placed && memory.mode != ModelManager::ResidencyMode::Disk && memory.params_backend == backend)
- bytes = add_size(bytes, memory.params_bytes);
- else if (compute)
- bytes = add_size(bytes, memory.largest_tensor);
- if (compute && workspace)
- bytes = add_size(bytes, entry.reserve);
+ bool RunPlan::move_model(size_t index, const std::string& backend) {
+ const auto previous = models_[index].backend;
+ models_[index].backend = backend;
+ bool moved = false;
+ try {
+ for (const auto& call : graph_.resources) {
+ const auto origin = origins_.find(call.expression);
+ if (call.deferred || origin == origins_.end() || origin->second != index)
+ continue;
+ auto args = call.arguments;
+ auto value = load_resource(call.expression, *call.operation, args);
+ if (!is_model_kind(value.type().kind) || !value.model_source)
+ continue;
+ auto& entry = models_[index];
+ identities_.erase({entry.key, entry.compute_automatic});
+ entry.key = value.model_source->key;
+ identities_[{entry.key, entry.compute_automatic}] = index;
+ entry.memory = model_from_value(value).model_weights->memory();
+ prepared_[call.expression] = std::move(value);
+ moved = true;
}
- peak = std::max(peak, bytes);
+ } catch (const Error& error) {
+ if (error.status == SD_STATUS_CANCELLED)
+ throw;
+ LOG_WARN("auto-fit cannot move %s to %s: %s", models_[index].name.c_str(), backend.c_str(), error.what());
+ } catch (const std::bad_alloc&) {
+ throw;
+ } catch (const std::exception& error) {
+ LOG_WARN("auto-fit cannot move %s to %s: %s", models_[index].name.c_str(), backend.c_str(), error.what());
}
- return peak;
+ if (!moved)
+ models_[index].backend = previous;
+ return moved;
}
- void RunPlan::place(size_t index, models::Model& model) {
- auto& entry = models_[index];
- auto& memory = entry.memory;
- if (!entry.automatic || memory.compute_backends.empty())
- return;
- auto target = memory.compute_backends.front();
- memory.params_backend = target;
- memory.mode = ModelManager::ResidencyMode::ParamBackend;
- bool fits = true;
- for (auto backend : memory.compute_backends)
- fits = fits && (sd_backend_is_cpu(backend) ? peak_bytes(backend, index, false) <= ram_budget_ && peak_bytes(backend, index) <= host_budget_ : peak_bytes(backend, index) <= budgets_[backend]);
- bool disk = false;
- if (!fits) {
- target = state_.context.backends->count("CPU") ? state_.context.backends->at("CPU").get() : nullptr;
- if (!target) {
- SDBackendManager backends(state_.context.backends);
- std::string error;
- if (!backends.init("cpu", "cpu", nullptr, &error))
- throw std::runtime_error(error);
- target = backends.runtime_backend(SDBackendModule::DIFFUSION);
+ void RunPlan::place_models() {
+ std::vector<size_t> order;
+ for (size_t i = 0; i < models_.size(); ++i) {
+ auto cached = state_.context.resources.find({models_[i].key, {}});
+ if (cached != state_.context.resources.end() && cached->second.value.lock())
+ order.push_back(i);
+ }
+ std::stable_sort(order.begin(), order.end(), [&](size_t a, size_t b) {
+ const auto& left = models_[a];
+ const auto& right = models_[b];
+ if (priority(left.kind) != priority(right.kind))
+ return priority(left.kind) < priority(right.kind);
+ return left.memory.params_bytes > right.memory.params_bytes;
+ });
+ auto device_of = [](const ModelEntry& entry) {
+ return entry.memory.compute_backends.empty()
+ ? std::string()
+ : sd::backend_fit::physical_device_key(ggml_backend_get_device(entry.memory.compute_backends.front()));
+ };
+ auto disk = [](const ModelEntry& entry) {
+ return entry.memory.mode == ModelManager::ResidencyMode::Disk;
+ };
+ // Weights stored in RAM count there; their compute device keeps only the reserve.
+ auto stored_in_ram = [](const ModelEntry& entry) {
+ return entry.memory.params_backend && sd_backend_is_cpu(entry.memory.params_backend);
+ };
+ struct Usage {
+ std::map<std::string, size_t> params, reserve;
+ size_t ram = 0;
+ };
+ auto usage = [&](size_t skip = SIZE_MAX) {
+ Usage result;
+ // Entries of one cached instance, explicit and automatic, count once.
+ std::set<std::string> counted;
+ for (auto index : order) {
+ const auto& entry = models_[index];
+ if (index == skip || entry.memory.compute_backends.empty() || disk(entry))
+ continue;
+ if (!counted.insert(entry.key).second)
+ continue;
+ // Split layouts are not known yet, so a split component counts in full on every card it uses.
+ std::set<std::string> devices;
+ for (auto backend : entry.memory.compute_backends) {
+ const auto device = sd::backend_fit::physical_device_key(ggml_backend_get_device(backend));
+ if (budgets_.count(device))
+ devices.insert(device);
+ }
+ const bool in_ram = devices.empty() || stored_in_ram(entry);
+ if (in_ram)
+ result.ram = add_size(result.ram, entry.memory.params_bytes);
+ for (const auto& device : devices) {
+ if (!in_ram)
+ result.params[device] = add_size(result.params[device], entry.memory.params_bytes);
+ result.reserve[device] = std::max(result.reserve[device], entry.reserve);
+ }
}
- memory.params_backend = target;
- disk = peak_bytes(target, index, false) > ram_budget_ || peak_bytes(target, index) > host_budget_;
- if (disk) {
- target = memory.compute_backends.front();
- memory.params_backend = target;
- memory.mode = ModelManager::ResidencyMode::Disk;
+ return result;
+ };
+ // Weights a GPU cannot hold move to RAM, which also holds the weights of CPU modules.
+ auto fits_usage = [&](const Usage& current) {
+ size_t overflow = current.ram;
+ for (const auto& [device, reserve] : current.reserve) {
+ const auto params = current.params.find(device);
+ const auto need = add_size(params == current.params.end() ? 0 : params->second, reserve);
+ const auto budget = budgets_.at(device);
+ overflow = add_size(overflow, need > budget ? need - budget : 0);
}
- }
- const auto name = disk ? std::string("disk") : std::string(ggml_backend_name(target));
- if (!model.place_params(name, target, disk)) {
- memory = model.model_weights->memory();
- LOG_DEBUG("preserved active or split placement for %s", entry.name.c_str());
+ return overflow <= ram_budget_;
+ };
+ auto fits = [&] { return fits_usage(usage()); };
+ // The GPU with the most room that holds all of a module's weights, or none.
+ auto target_of = [&](size_t index) {
+ const auto& entry = models_[index];
+ const auto others = usage(index);
+ std::string best;
+ size_t best_free = 0;
+ for (const auto& [device, budget] : budgets_) {
+ if (device == device_of(entry))
+ continue;
+ const auto params = others.params.count(device) ? others.params.at(device) : 0;
+ const auto reserve = std::max(others.reserve.count(device) ? others.reserve.at(device) : 0, entry.reserve);
+ const auto used = add_size(params, reserve);
+ const auto free = budget > used ? budget - used : 0;
+ if (entry.memory.params_bytes <= free && (best.empty() || free > best_free)) {
+ best = device;
+ best_free = free;
+ }
+ }
+ return best;
+ };
+ auto fits_after = [&](size_t index, const std::string& device) {
+ const auto& entry = models_[index];
+ auto current = usage(index);
+ if (stored_in_ram(entry))
+ current.ram = add_size(current.ram, entry.memory.params_bytes);
+ else
+ current.params[device] = add_size(current.params[device], entry.memory.params_bytes);
+ current.reserve[device] = std::max(current.reserve[device], entry.reserve);
+ return fits_usage(current);
+ };
+
+ // Lower-priority modules move first, and only to a GPU that holds all their weights. A move
+ // that alone makes the plan fit goes before one that only reduces the overflow.
+ std::set<size_t> tried;
+ while (budgets_.size() > 1 && !fits()) {
+ std::vector<std::pair<size_t, std::string>> moves;
+ for (auto it = order.rbegin(); it != order.rend(); ++it) {
+ const auto& entry = models_[*it];
+ if (tried.count(*it) || !entry.automatic || !entry.compute_automatic || entry.kind == Kind::Denoiser ||
+ entry.memory.split || entry.memory.compute_backends.size() != 1 || !budgets_.count(device_of(entry)))
+ continue;
+ auto target = target_of(*it);
+ if (!target.empty())
+ moves.emplace_back(*it, std::move(target));
+ }
+ if (moves.empty())
+ break;
+ auto chosen = std::find_if(moves.begin(), moves.end(), [&](const auto& move) { return fits_after(move.first, move.second); });
+ if (chosen == moves.end())
+ chosen = moves.begin();
+ tried.insert(chosen->first);
+ move_model(chosen->first, device_names_.at(chosen->second));
}
}
@@ -258,35 +354,20 @@ namespace sd::dgl {
for (const auto& call : graph_.resources) {
if (call.expression != expression)
continue;
- const bool known = origins_.count(expression) != 0;
- const auto index = add_model(call, value);
+ const auto origin = origins_.find(expression);
+ const size_t before = origin == origins_.end() ? SIZE_MAX : origin->second;
+ const auto index = add_model(call, value);
if (index == SIZE_MAX)
break;
- auto& model = model_from_value(value);
- auto current = model.model_weights->memory();
- auto& entry = models_[index];
- if (known && current.params_bytes == entry.memory.params_bytes && current.compute_backends == entry.memory.compute_backends) {
- const bool disk = entry.memory.mode == ModelManager::ResidencyMode::Disk;
- if (entry.automatic && entry.memory.params_backend && !model.place_params(disk ? "disk" : ggml_backend_name(entry.memory.params_backend), entry.memory.params_backend, disk))
- entry.memory = std::move(current);
- break;
+ auto current = model_from_value(value).model_weights->memory();
+ auto& entry = models_[index];
+ const bool changed = before != index || current.params_bytes != entry.memory.params_bytes ||
+ current.compute_backends != entry.memory.compute_backends;
+ entry.memory = std::move(current);
+ if (changed) {
+ update_priorities();
+ LOG_DEBUG("updated the remaining plan for %s", entry.name.c_str());
}
- entry.memory = std::move(current);
- for (auto backend : entry.memory.compute_backends)
- if (!sd_backend_is_cpu(backend) && !budgets_.count(backend)) {
- size_t free = 0, total = 0;
- ggml_backend_dev_memory(ggml_backend_get_device(backend), &free, &total);
- auto available = state_.context.models->available_vram_for_fit(backend, free, total);
- if (!state_.context.models->max_vram_bytes(backend))
- available -= std::min(available, 512 * MiB);
- budgets_[backend] = available;
- }
- const auto ram = state_.context.models->available_ram_for_fit();
- ram_budget_ = ram.weights;
- host_budget_ = ram.total;
- place_models();
- update_priorities();
- LOG_DEBUG("updated the remaining plan for %s", entry.name.c_str());
break;
}
}
diff --git a/src/dgl/run_plan.h b/src/dgl/run_plan.h
index 42b3957..f8d958b 100644
--- a/src/dgl/run_plan.h
+++ b/src/dgl/run_plan.h
@@ -1,6 +1,8 @@
#ifndef __SD_DGL_RUN_PLAN_H__
#define __SD_DGL_RUN_PLAN_H__
+#include <utility>
+
#include "graph.h"
#include "model_manager.h"
@@ -13,8 +15,10 @@ namespace sd::dgl {
Kind kind;
ModelManager::ResourceMemory memory;
size_t reserve = 0;
- bool automatic = false;
- bool placed = false;
+ // Only components with unset params and compute backends can move.
+ bool automatic = false;
+ bool compute_automatic = false;
+ std::string backend;
};
const Graph& graph_;
RunState& state_;
@@ -24,23 +28,25 @@ namespace sd::dgl {
std::map<const Expr*, Value> prepared_;
std::map<const Expr*, size_t> origins_;
std::vector<ModelEntry> models_;
- std::map<std::string, size_t> identities_;
- std::map<ggml_backend_t, size_t> budgets_;
- size_t ram_budget_ = 0;
- size_t host_budget_ = 0;
+ // An explicitly placed model and an automatically placed one can share a resource key.
+ std::map<std::pair<std::string, bool>, size_t> identities_;
+ // Keyed by physical GPU.
+ std::map<std::string, size_t> budgets_;
+ std::map<std::string, std::string> device_names_;
+ size_t ram_budget_ = 0;
std::string default_backend_;
size_t add_model(const Graph::ResourceCall& call, const Value& value);
bool active(const Graph::ResourceUse& use) const;
+ void update_budgets();
void place_models();
- void place(size_t index, models::Model& model);
- size_t peak_bytes(ggml_backend_t backend, size_t candidate, bool workspace = true) const;
+ bool move_model(size_t index, const std::string& backend);
void update_priorities();
public:
RunPlan(const Graph& graph, RunState& state);
~RunPlan();
- Value load_resource(const Registry::Entry& operation, Values& args);
+ Value load_resource(const Expr* expression, const Registry::Entry& operation, Values& args);
void enter(const Expr* statement, const std::vector<const Expr*>& call_path = {}, bool after = false);
void resource_loaded(const Expr* expression, const Value& value);
};
diff --git a/src/model/adapter/lora.hpp b/src/model/adapter/lora.hpp
index 352f2d4..0b6a7ad 100644
--- a/src/model/adapter/lora.hpp
+++ b/src/model/adapter/lora.hpp
@@ -1094,9 +1094,14 @@ struct LoraModel : public GGMLRunner {
};
const bool success = GGMLRunner::compute(get_graph, n_threads, false, true, read_outputs).has_value();
if (!success) {
- LOG_ERROR("LoRA graph execution failed");
+ const bool capacity = !device_memory_error().empty() || last_compute_status() == GGML_STATUS_ALLOC_FAILED;
+ if (capacity && capacity_failure_recoverable)
+ LOG_DEBUG("LoRA graph did not fit in device memory");
+ else
+ LOG_ERROR("LoRA graph execution failed");
+ } else {
+ stat(!warn_unused);
}
- stat(!warn_unused);
int8_merged_weights.clear();
int8_merge_status.clear();
original_tensor_to_final_tensor.clear();
diff --git a/src/model/adapter/lora_merge.cpp b/src/model/adapter/lora_merge.cpp
new file mode 100644
index 0000000..1e8af58
--- /dev/null
+++ b/src/model/adapter/lora_merge.cpp
@@ -0,0 +1,140 @@
+#include "model/adapter/lora_merge.h"
+
+#include "core/util.h"
+#include "model/adapter/lora.hpp"
+
+namespace sd::lora {
+ bool merge_candidates(const std::vector<ModelManager::LoraSpec>& loras,
+ const std::vector<MergeCandidate>& candidates,
+ const MergeContext& context,
+ MergeProgress& progress,
+ std::vector<size_t>& merged,
+ bool& capacity_failure) {
+ struct Group {
+ MergeTarget target;
+ std::vector<size_t> members;
+ };
+ std::map<MergeProgress::key_type, Group> groups;
+ for (size_t index = 0; index < candidates.size(); ++index) {
+ const auto& candidate = candidates[index];
+ auto& group = groups[{candidate.compute_backend, candidate.params_backend, candidate.residency}];
+ group.target.compute_backend = candidate.compute_backend;
+ group.target.params_backend = candidate.params_backend;
+ group.target.residency = candidate.residency;
+ group.members.push_back(index);
+ if (candidate.scale_only)
+ continue;
+ if (candidate.int8_scale)
+ group.target.int8_weights[candidate.tensor] = {candidate.int8_scale, candidate.convrot_group_size};
+ group.target.tensors[candidate.name] = candidate.tensor;
+ }
+ for (auto& [key, group] : groups) {
+ if (!merge(loras, group.target, context, progress[key], capacity_failure))
+ return false;
+ merged.insert(merged.end(), group.members.begin(), group.members.end());
+ }
+ return true;
+ }
+
+ static std::string adapter_id(const ModelManager::LoraSpec& lora) {
+ return lora.is_high_noise ? "|high_noise|" + lora.path : lora.path;
+ }
+
+ bool merge(const std::vector<ModelManager::LoraSpec>& loras,
+ const MergeTarget& target,
+ const MergeContext& context,
+ GroupProgress& progress,
+ bool& capacity_failure) {
+ if (target.tensors.empty())
+ return true;
+ auto update_bytes = [](const ggml_tensor* tensor) { return size_t(ggml_nelements(tensor)) * sizeof(float); };
+ // Adapters apply in order to the same targets.
+ for (; progress.completed < loras.size(); ++progress.completed, progress.written.clear()) {
+ const auto& spec = loras[progress.completed];
+ auto lora = spec.prepared.lock();
+ if (lora && (lora->backend() != target.compute_backend || lora->params_backend != target.params_backend))
+ lora.reset();
+ const bool temporary = !lora;
+ if (temporary) {
+ // The temporary runner is destroyed before the merge returns.
+ lora = std::make_shared<LoraModel>(adapter_id(spec), target.compute_backend, target.params_backend,
+ context.adapter_weights(), spec.file_id, context.version, target.residency);
+ }
+ LoraModel::filter_t filter = nullptr;
+ if (!spec.tensor_name_prefix_filter.empty()) {
+ filter = [&](const std::string& tensor_name) {
+ return starts_with(tensor_name, spec.tensor_name_prefix_filter);
+ };
+ }
+ if (temporary && !lora->init_params(context.n_threads, filter)) {
+ LOG_WARN("load lora tensors from %s failed", spec.path.c_str());
+ if (spec.required)
+ return false;
+ continue;
+ }
+ if (lora->lora_tensors.empty()) {
+ if (spec.required) {
+ LOG_ERROR("required lora has no tensors: %s", spec.path.c_str());
+ return false;
+ }
+ continue;
+ }
+ lora->multiplier = spec.multiplier;
+ // A failed batch is split below, so its capacity failure is not an error yet.
+ struct Recoverable {
+ LoraModel& lora;
+ ~Recoverable() { lora.set_capacity_failure_recoverable(false); }
+ } recoverable{*lora};
+ lora->set_capacity_failure_recoverable(true);
+ // Batches take targets in order; a successful batch moves the scan past its targets.
+ auto next = target.tensors.begin();
+ while (progress.written.size() < target.tensors.size()) {
+ std::map<std::string, ggml_tensor*> batch;
+ std::map<ggml_tensor*, LoraInt8Weight> int8_weights;
+ size_t bytes = 0;
+ auto end = next;
+ for (; end != target.tensors.end(); ++end) {
+ const auto& [name, tensor] = *end;
+ if (progress.written.count(name) != 0)
+ continue;
+ const size_t size = update_bytes(tensor);
+ if (!batch.empty() && size > progress.batch_bytes - std::min(bytes, progress.batch_bytes))
+ break;
+ batch.emplace(name, tensor);
+ bytes += size;
+ const auto int8 = target.int8_weights.find(tensor);
+ if (int8 != target.int8_weights.end())
+ int8_weights.emplace(int8->first, int8->second);
+ }
+ if (batch.empty())
+ break;
+ if (lora->apply(batch, *context.model_tensor_names, context.version, context.n_threads, false, int8_weights)) {
+ for (const auto& entry : batch)
+ progress.written.insert(entry.first);
+ next = end;
+ continue;
+ }
+ capacity_failure = !lora->device_memory_error().empty() ||
+ lora->last_compute_status() == GGML_STATUS_ALLOC_FAILED;
+ if (capacity_failure && batch.size() == 1) {
+ progress.capacity_error = lora->device_memory_error().empty() ? "graph allocation failed"
+ : lora->device_memory_error();
+ LOG_INFO("lora %s: one target does not fit in device memory", spec.path.c_str());
+ }
+ if (!capacity_failure || batch.size() == 1)
+ return false;
+ // A merge graph has no cut points, so a capacity failure happens before it writes any
+ // target. Merge fewer targets per graph.
+ capacity_failure = false;
+ progress.batch_bytes = std::max<size_t>(bytes / 2, 1);
+ LOG_INFO("merging lora %s in smaller batches (%.2f MB of updates per graph)", spec.path.c_str(),
+ progress.batch_bytes / (1024.0 * 1024.0));
+ }
+ if (temporary)
+ lora->release_loaded_tensors();
+ else
+ lora->runner_end();
+ }
+ return true;
+ }
+}
diff --git a/src/model/adapter/lora_merge.h b/src/model/adapter/lora_merge.h
new file mode 100644
index 0000000..4640d94
--- /dev/null
+++ b/src/model/adapter/lora_merge.h
@@ -0,0 +1,86 @@
+#ifndef __SD_LORA_MERGE_H__
+#define __SD_LORA_MERGE_H__
+
+#include <cstddef>
+#include <functional>
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+#include <tuple>
+#include <vector>
+
+#include "model/adapter/lora_ops.h"
+#include "model_manager.h"
+
+namespace sd::lora {
+ // Weights of one compute device to merge adapters into. The residency layer selects them and
+ // supplies the copies to write; it records the merged version after a successful merge.
+ struct MergeTarget {
+ ggml_backend_t compute_backend = nullptr;
+ // Where adapter weights live while merging.
+ ggml_backend_t params_backend = nullptr;
+ ModelManager::ResidencyMode residency = ModelManager::ResidencyMode::ParamBackend;
+ std::map<std::string, ggml_tensor*> tensors;
+ // INT8 weights and the scales that dequantize them.
+ std::map<ggml_tensor*, LoraInt8Weight> int8_weights;
+ };
+
+ struct MergeContext {
+ SDVersion version = VERSION_COUNT;
+ int n_threads = 0;
+ // Every weight name of the model, for adapter name matching.
+ const std::set<std::string>* model_tensor_names = nullptr;
+ // Registers a temporary adapter's weights with the residency layer.
+ std::function<std::shared_ptr<ModelManager::ResourceHandle>()> adapter_weights;
+ };
+
+ // A weight the residency layer offers for merging: the copy to write and where it computes.
+ struct MergeCandidate {
+ std::string name;
+ ggml_tensor* tensor = nullptr;
+ ggml_backend_t compute_backend = nullptr;
+ ggml_backend_t params_backend = nullptr;
+ ModelManager::ResidencyMode residency = ModelManager::ResidencyMode::ParamBackend;
+ // An INT8 weight with the scale that dequantizes it.
+ ggml_tensor* int8_scale = nullptr;
+ int convrot_group_size = 0;
+ // The scale of an INT8 weight; it is written with its weight and records the same version.
+ bool scale_only = false;
+ };
+
+ // How far a target group got, kept across a retry so no adapter is merged twice.
+ struct GroupProgress {
+ // Adapters written into every target.
+ size_t completed = 0;
+ // Targets that already hold the next adapter.
+ std::set<std::string> written;
+ // Upper bound on the F32 update bytes one merge graph handles. A whole model merged at once
+ // would otherwise need workspace for every update; it shrinks further when a merge runs
+ // out of device memory.
+ size_t batch_bytes = size_t(4) << 30;
+ // Why a single target did not fit, when device memory stopped the merge.
+ std::string capacity_error;
+ };
+ using MergeProgress = std::map<std::tuple<ggml_backend_t, ggml_backend_t, ModelManager::ResidencyMode>, GroupProgress>;
+
+ // Groups the candidates by compute device and merges each group. merged receives the candidates
+ // whose group holds every adapter, including groups finished before a failure.
+ bool merge_candidates(const std::vector<ModelManager::LoraSpec>& loras,
+ const std::vector<MergeCandidate>& candidates,
+ const MergeContext& context,
+ MergeProgress& progress,
+ std::vector<size_t>& merged,
+ bool& capacity_failure);
+
+ // Applies the adapters in order, resuming from progress. Each adapter is merged in batches of
+ // targets; a batch that runs out of device memory is split until a single target remains.
+ // capacity_failure reports that device memory, not the adapter, stopped the merge.
+ bool merge(const std::vector<ModelManager::LoraSpec>& loras,
+ const MergeTarget& target,
+ const MergeContext& context,
+ GroupProgress& progress,
+ bool& capacity_failure);
+}
+
+#endif // __SD_LORA_MERGE_H__
diff --git a/src/model_manager.cpp b/src/model_manager.cpp
index 8815846..13f98e3 100644
--- a/src/model_manager.cpp
+++ b/src/model_manager.cpp
@@ -6,12 +6,19 @@
#include <cstdint>
#include <iterator>
#include <mutex>
+#include <set>
#include <tuple>
+#include <unordered_map>
#include <unordered_set>
#include "core/ggml_extend_backend.h"
#include "core/util.h"
#include "model/adapter/lora.hpp"
+#include "model/adapter/lora_merge.h"
+#include "weights/accounting.h"
+#include "weights/capacity.h"
+#include "weights/weight_copy.h"
+#include "weights/weight_reader.h"
static size_t aligned_offset(const void* buffer, size_t offset, size_t alignment) {
GGML_ASSERT(alignment != 0 && (alignment & (alignment - 1)) == 0);
@@ -19,6 +26,11 @@ static size_t aligned_offset(const void* buffer, size_t offset, size_t alignment
return offset + align;
}
+using sd::weights::BackendBuffer;
+using HostWeightCopies = sd::weights::WeightCopies;
+using sd::weights::copy_weights;
+using sd::weights::weight_copy_bytes;
+
static bool lora_specs_equal(const std::vector<ModelManager::LoraSpec>& lhs,
const std::vector<ModelManager::LoraSpec>& rhs) {
if (lhs.size() != rhs.size()) {
@@ -37,10 +49,6 @@ static bool lora_specs_equal(const std::vector<ModelManager::LoraSpec>& lhs,
return true;
}
-static std::string lora_id(const ModelManager::LoraSpec& lora) {
- return lora.is_high_noise ? "|high_noise|" + lora.path : lora.path;
-}
-
static bool backend_supports_host_buffer(ggml_backend_t backend) {
if (backend == nullptr) {
return false;
@@ -119,7 +127,7 @@ bool ModelManager::remove_resource(ResourceId id) {
if (found == resources_.end() || found->second.applying_loras_)
return false;
std::unordered_set<TensorState*> states;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource == &found->second)
states.insert(state.get());
}
@@ -207,8 +215,8 @@ bool ModelManager::set_loras(Resource& resource, std::vector<LoraSpec> loras, SD
resource.loras_ = std::move(loras);
return true;
}
- if (!runtime_owners_.empty() || std::any_of(tensor_states_.begin(), tensor_states_.end(), [&](const auto& state) {
- return state->resource == &resource && state->pin_count != 0;
+ if (!runtime_owners_.empty() || std::any_of(store_.tensor_states().begin(), store_.tensor_states().end(), [&](const auto& state) {
+ return state->resource == &resource && state->pin_count() != 0;
})) {
LOG_ERROR("cannot change LoRA configuration during execution");
return false;
@@ -224,7 +232,7 @@ bool ModelManager::set_loras(Resource& resource, std::vector<LoraSpec> loras, SD
std::set<std::string> ModelManager::tensor_names(const Resource& resource) const {
std::set<std::string> names;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource == &resource && state->component != ModelComponent::LoRA &&
(!resource.shared_weights_key_.empty() || resource.model_sources_.count(state->source_file) == 0)) {
names.insert(state->name);
@@ -297,25 +305,26 @@ bool ModelManager::register_param_tensors(Resource& resource, ModelComponent com
if (tensor == nullptr) {
continue;
}
- if (tensor_states_by_tensor_.count(tensor) != 0 || !new_tensors.insert(tensor).second) {
+ if (store_.tensor_index().count(tensor) != 0 || !new_tensors.insert(tensor).second) {
LOG_ERROR("model manager tensor name '%s' is already registered", name.c_str());
return false;
}
ggml_set_name(tensor, name.c_str());
- auto state = std::make_unique<TensorState>();
- state->resource = &resource;
- state->name = name;
- state->tensor = tensor;
- state->component = component;
- state->source_file = source_file;
- state->source_version = source_version;
- state->sources = find_tensor_sources(*state, sources);
- state->is_int8_weight = !state->sources.empty() && state->sources.front().is_int8_tensorwise;
- state->residency_mode = residency_mode;
- state->compute_backend = compute_backend;
- state->params_backend = params_backend;
- auto split_buffer = resource.split_buffer_types_.find(compute_backend);
+ auto state = std::make_unique<TensorState>();
+ state->resource = &resource;
+ state->name = name;
+ state->tensor = tensor;
+ state->component = component;
+ state->source_file = source_file;
+ state->source_version = source_version;
+ state->sources = find_tensor_sources(*state, sources);
+ state->is_int8_weight = !state->sources.empty() && state->sources.front().is_int8_tensorwise;
+ state->residency_mode = residency_mode;
+ state->compute_backend = compute_backend;
+ state->preferred_backend = params_backend;
+ store_.reset_location(*state);
+ auto split_buffer = resource.split_buffer_types_.find(compute_backend);
if (allow_split_buffer && split_buffer != resource.split_buffer_types_.end()) {
state->split_buffer_type = split_buffer->second;
}
@@ -345,17 +354,14 @@ bool ModelManager::register_param_tensors(Resource& resource, ModelComponent com
}
resolved_tensor_states_.clear();
- for (auto& state : new_states) {
- TensorState* registered_state = state.get();
- tensor_states_by_tensor_[registered_state->tensor] = registered_state;
- tensor_states_.push_back(std::move(state));
- }
+ for (auto& state : new_states)
+ store_.add_state(std::move(state));
return true;
}
bool ModelManager::unregister_param_tensors(Resource& resource, ModelComponent component, size_t* registered_tensor_size) {
std::unordered_set<TensorState*> states;
- for (auto& state : tensor_states_) {
+ for (auto& state : store_.tensor_states()) {
if (state->resource == &resource && state->component == component)
states.insert(state.get());
}
@@ -369,8 +375,8 @@ bool ModelManager::unregister_param_tensors(const std::vector<ggml_tensor*>& ten
bool ModelManager::unregister_param_tensors(const std::vector<ggml_tensor*>& tensors, const Resource* resource) {
std::unordered_set<TensorState*> states;
for (auto tensor : tensors) {
- auto found = tensor_states_by_tensor_.find(tensor);
- if (found != tensor_states_by_tensor_.end()) {
+ auto found = store_.tensor_index().find(tensor);
+ if (found != store_.tensor_index().end()) {
if (resource && found->second->resource != resource) {
LOG_ERROR("cannot unregister a tensor from a different model resource");
return false;
@@ -385,11 +391,11 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
size_t* registered_tensor_size,
bool keep_registration) {
size_t released_size = 0;
- for (auto& state : tensor_states_) {
+ for (auto& state : store_.tensor_states()) {
if (state == nullptr || target_states.count(state.get()) == 0) {
continue;
}
- if (state->pin_count > 0) {
+ if (state->pin_count() > 0) {
LOG_ERROR("model manager cannot unregister active %s tensor '%s'",
model_component_name(state->component),
state->name.c_str());
@@ -406,7 +412,7 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
std::vector<ParamsStorageBlock*> storage_blocks_to_release;
std::unordered_set<TensorState*> affected_storage_states;
- for (const auto& block : params_storage_blocks_) {
+ for (const auto& block : store_.storage_blocks()) {
if (block == nullptr) {
continue;
}
@@ -442,25 +448,28 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
}
// An idle staging block must be released as a whole before unregistering any member.
auto staging_states = target_states;
- for (const auto& block : compute_staging_blocks_) {
+ for (const auto& block : store_.compute_blocks()) {
const bool intersects = std::any_of(block->staged_tensors.begin(), block->staged_tensors.end(), [&](const auto& entry) {
return entry.first && target_states.count(entry.first);
});
const bool idle = std::all_of(block->staged_tensors.begin(), block->staged_tensors.end(), [](const auto& entry) {
- return !entry.first || entry.first->pin_count == 0;
+ return !entry.first || entry.first->pin_count() == 0;
});
if (intersects && idle)
for (const auto& entry : block->staged_tensors)
if (entry.first)
staging_states.insert(entry.first);
}
- release_compute_staging_blocks(false, &staging_states);
+ store_.release_compute_staging_blocks(false, &staging_states);
- for (TensorState* state : affected_storage_states) {
+ // A target whose staging block another weight still pins keeps its staged copy.
+ auto active_states = affected_storage_states;
+ active_states.insert(target_states.begin(), target_states.end());
+ for (TensorState* state : active_states) {
if (state == nullptr) {
continue;
}
- if (state->pin_count > 0 || state->staged_to_compute_backend) {
+ if (state->pin_count() > 0 || state->staged()) {
LOG_ERROR("model manager cannot unregister %s while tensor '%s' is active",
model_component_name(state->component),
state->name.c_str());
@@ -470,28 +479,19 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
for (ParamsStorageBlock* block : storage_blocks_to_release) {
if (block != nullptr) {
- free_params_storage_block(*block);
- erase_params_storage_block(block);
- }
- }
- for (auto& block : params_storage_blocks_) {
- if (block->shared) {
- auto& states = block->states;
- states.erase(std::remove_if(states.begin(), states.end(), [&](auto* state) {
- return target_states.count(state) != 0;
- }),
- states.end());
+ store_.free_params_storage_block(*block);
+ store_.erase_params_storage_block(block);
}
}
+ store_.leave_shared_blocks(target_states);
resolved_tensor_states_.clear();
if (keep_registration) {
for (auto* state : target_states) {
- state->tensor->buffer = nullptr;
- state->tensor->data = nullptr;
- state->tensor->extra = nullptr;
- state->loaded_to_params_backend = false;
- state->applied_lora_epoch = UINT64_MAX;
+ state->tensor->buffer = nullptr;
+ state->tensor->data = nullptr;
+ state->tensor->extra = nullptr;
+ store_.forget(*state);
}
return true;
}
@@ -501,19 +501,7 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
state->lora_int8_partner = nullptr;
}
}
- for (auto it = tensor_states_by_tensor_.begin(); it != tensor_states_by_tensor_.end();) {
- if (target_states.count(it->second) > 0) {
- it = tensor_states_by_tensor_.erase(it);
- } else {
- ++it;
- }
- }
- tensor_states_.erase(std::remove_if(tensor_states_.begin(),
- tensor_states_.end(),
- [&](const std::unique_ptr<TensorState>& s) {
- return s == nullptr || target_states.count(s.get()) > 0;
- }),
- tensor_states_.end());
+ store_.remove_states(target_states);
if (registered_tensor_size != nullptr) {
if (released_size > *registered_tensor_size) {
@@ -528,7 +516,7 @@ bool ModelManager::unregister_tensor_states(const std::unordered_set<TensorState
ModelManager::ResourceMemory ModelManager::resource_memory(const Resource& resource) const {
ResourceMemory result;
result.split = resource.layer_split_;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource != &resource || !state->tensor)
continue;
const auto bytes = ggml_nbytes(state->tensor);
@@ -536,10 +524,21 @@ ModelManager::ResourceMemory ModelManager::resource_memory(const Resource& resou
result.largest_tensor = std::max(result.largest_tensor, bytes);
if (state->compute_backend && std::find(result.compute_backends.begin(), result.compute_backends.end(), state->compute_backend) == result.compute_backends.end())
result.compute_backends.push_back(state->compute_backend);
- result.params_backend = state->params_backend;
+ result.params_backend = state->preferred_backend;
result.mode = state->residency_mode;
result.split = result.split || state->split_buffer_type || state->tensor->view_src;
}
+ // Split participants are configured before every tensor is assigned to them.
+ auto add_backend = [&](ggml_backend_t backend) {
+ if (backend && std::find(result.compute_backends.begin(), result.compute_backends.end(), backend) == result.compute_backends.end())
+ result.compute_backends.push_back(backend);
+ };
+ for (auto backend : resource.layer_split_backends_)
+ add_backend(backend);
+ for (const auto& [_, devices] : resource.split_buffer_limits_) {
+ for (const auto& [backend, limit] : devices)
+ add_backend(backend);
+ }
return result;
}
@@ -547,8 +546,8 @@ bool ModelManager::place_resource_params(Resource& resource, ggml_backend_t back
if (resource.layer_split_)
return false;
std::unordered_set<TensorState*> changed;
- for (const auto& state : tensor_states_)
- if (state->resource == &resource && (state->params_backend != backend || state->residency_mode != mode)) {
+ for (const auto& state : store_.tensor_states())
+ if (state->resource == &resource && (state->preferred_backend != backend || state->residency_mode != mode)) {
if (state->split_buffer_type || state->tensor->view_src)
return false;
changed.insert(state.get());
@@ -556,9 +555,10 @@ bool ModelManager::place_resource_params(Resource& resource, ggml_backend_t back
if (!changed.empty() && !unregister_tensor_states(changed, nullptr, true))
return false;
for (auto* state : changed) {
- state->params_backend = backend;
+ state->preferred_backend = backend;
state->residency_mode = mode;
state->params_follow_compute_backend = mode == ResidencyMode::Disk;
+ store_.reset_location(*state);
}
return true;
}
@@ -566,31 +566,86 @@ bool ModelManager::place_resource_params(Resource& resource, ggml_backend_t back
size_t ModelManager::next_weight_use(const TensorState& state) const {
if (planned_next_use_.empty())
return 0;
- const auto found = planned_next_use_.find(state.resource->shared_weights_key_);
+ const auto found = planned_next_use_.find(resource_of(state).shared_weights_key_);
return found == planned_next_use_.end() ? SIZE_MAX : found->second;
}
bool ModelManager::load_all_params_eagerly(const Resource& resource) {
- std::vector<TensorState*> all_states;
- all_states.reserve(tensor_states_.size());
- for (const auto& s : tensor_states_) {
- if (s->resource == &resource) {
- all_states.push_back(s.get());
+ // Eager loading only moves file reads ahead. Weights take the highest location on their
+ // residency chain with free capacity and never reclaim resident weights; the rest load on use.
+ constexpr size_t compute_reserve = 2048ULL * 1024 * 1024;
+ std::map<ggml_backend_t, size_t> device_bytes;
+ size_t host_bytes = 0;
+ size_t candidates = 0;
+ std::vector<TensorState*> placed;
+ for (const auto& state : store_.tensor_states()) {
+ if (state->resource != &resource || should_ignore(*state) || state->sources.empty() ||
+ state->loaded() || state->staged())
+ continue;
+ ++candidates;
+ if (state->split_buffer_type) {
+ // The row split is not known yet, so every participant must have room for the whole weight.
+ const auto buft = params_buffer_type_for(*state);
+ if (!buft)
+ return false;
+ const size_t bytes = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, state->tensor), ggml_backend_buft_get_alignment(buft));
+ const auto devices = split_devices_for({state.get()});
+ const bool fits = !devices.empty() && std::all_of(devices.begin(), devices.end(), [&](const auto& device) {
+ return check_capacity({device.first, 0, device_bytes[device.first] + bytes + compute_reserve, 0, device.second}, {},
+ DeviceMemoryCheck::Inspect)
+ .fits();
+ });
+ if (fits) {
+ for (const auto& device : devices)
+ device_bytes[device.first] += bytes;
+ placed.push_back(state.get());
+ }
+ continue;
+ }
+ if (state->tensor->view_src || !state->compute_backend) {
+ placed.push_back(state.get());
+ continue;
+ }
+ for (auto backend = home_backend(*state); backend; backend = next_residency_backend(*state, backend)) {
+ const auto buft = params_buffer_type_for(*state, backend);
+ if (!buft)
+ return false;
+ const size_t bytes = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, state->tensor), ggml_backend_buft_get_alignment(buft));
+ bool fits = false;
+ if (ggml_backend_buft_is_host(buft)) {
+ size_t available = 0;
+ fits = fits_host_capacity(host_bytes + bytes, true, 0, available);
+ if (fits)
+ host_bytes += bytes;
+ } else {
+ auto& pending = device_bytes[backend];
+ fits = check_capacity({backend, 0, pending + bytes + compute_reserve}, {}, DeviceMemoryCheck::Inspect).fits();
+ if (fits)
+ pending += bytes;
+ }
+ if (fits) {
+ store_.move_to(*state, backend);
+ placed.push_back(state.get());
+ break;
+ }
}
}
- return load_tensors_to_params_backend(all_states);
+ if (placed.size() != candidates)
+ LOG_VERBOSE("model manager eagerly loaded %zu weight tensors; the rest load on first use", placed.size());
+ return load_tensors_to_params_backend(placed);
}
bool ModelManager::validate_registered_tensors(const Resource& resource) {
bool ok = true;
std::vector<TensorState*> share;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource != &resource)
continue;
bool state_ok = validate_tensor(*state);
if (state_ok) {
state->metadata_validated = true;
- if (!resource.shared_weights_key_.empty() && !state->loaded_to_params_backend)
+ if (!resource.shared_weights_key_.empty() && !state->loaded() &&
+ !state->staged())
share.push_back(state.get());
}
ok = state_ok && ok;
@@ -622,7 +677,7 @@ bool ModelManager::validate_param_tensors(const std::vector<ggml_tensor*>& tenso
return true;
}
-bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*>& states) {
+bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*>& states, bool* capacity_failure) {
std::vector<TensorState*> need_load;
need_load.reserve(states.size());
for (TensorState* state : states) {
@@ -635,11 +690,13 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*
}
state->metadata_validated = true;
}
- if (!state->loaded_to_params_backend) {
+ if (!state->loaded() && !state->staged()) {
need_load.push_back(state);
}
}
reuse_shared_weights(need_load);
+ const auto stages_from_file = [](const TensorState* state) { return state->param_source() == ParamSource::ModelFile; };
+ need_load.erase(std::remove_if(need_load.begin(), need_load.end(), stages_from_file), need_load.end());
if (need_load.empty()) {
return true;
}
@@ -648,8 +705,8 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*
if (!mmap_params(need_load, created_storage_blocks)) {
for (ParamsStorageBlock* block : created_storage_blocks) {
if (block != nullptr) {
- free_params_storage_block(*block);
- erase_params_storage_block(block);
+ store_.free_params_storage_block(*block);
+ store_.erase_params_storage_block(block);
}
}
return false;
@@ -663,12 +720,13 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*
}
}
- if (!alloc_params_buffers(need_alloc, states, created_storage_blocks) ||
- !load_tensors(need_load)) {
+ const bool allocated = alloc_params_buffers(need_alloc, states, created_storage_blocks, capacity_failure);
+ need_load.erase(std::remove_if(need_load.begin(), need_load.end(), stages_from_file), need_load.end());
+ if (!allocated || !load_tensors(need_load)) {
for (ParamsStorageBlock* block : created_storage_blocks) {
if (block != nullptr) {
- free_params_storage_block(*block);
- erase_params_storage_block(block);
+ store_.free_params_storage_block(*block);
+ store_.erase_params_storage_block(block);
}
}
return false;
@@ -698,16 +756,16 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*
std::set<std::string_view> shared_groups;
bool shared_loras = false;
for (auto* state : need_load) {
- if (!state->resource->shared_weights_key_.empty()) {
- shared_groups.insert(state->resource->shared_weights_key_);
+ if (!resource_of(*state).shared_weights_key_.empty()) {
+ shared_groups.insert(resource_of(*state).shared_weights_key_);
shared_loras |= state->component == ModelComponent::LoRA;
}
}
if (!shared_groups.empty()) {
std::vector<TensorState*> share;
- for (const auto& state : tensor_states_) {
- if (!state->loaded_to_params_backend && state->metadata_validated &&
- (shared_groups.count(state->resource->shared_weights_key_) != 0 ||
+ for (const auto& state : store_.tensor_states()) {
+ if (!state->loaded() && !state->staged() && state->metadata_validated &&
+ (shared_groups.count(resource_of(*state).shared_weights_key_) != 0 ||
(shared_loras && state->component == ModelComponent::LoRA)))
share.push_back(state.get());
}
@@ -720,16 +778,213 @@ bool ModelManager::load_tensors_to_params_backend(const std::vector<TensorState*
bool ModelManager::has_lora_int8_pair(const TensorState& state) {
return state.lora_int8_partner &&
- state.resource->lora_targets_.count(state.is_int8_weight ? state.name : state.lora_int8_partner->name) != 0;
+ resource_of(state).lora_targets_.count(state.is_int8_weight ? state.name : state.lora_int8_partner->name) != 0;
}
bool ModelManager::needs_lora_staging(const TensorState& state) {
return state.component != ModelComponent::LoRA &&
- (has_lora_int8_pair(state) || (!state.resource->shared_weights_key_.empty() &&
- state.resource->lora_targets_.count(state.name) != 0));
+ (has_lora_int8_pair(state) || (!resource_of(state).shared_weights_key_.empty() &&
+ resource_of(state).lora_targets_.count(state.name) != 0));
+}
+
+bool ModelManager::compute_params_resident(const TensorState& state) {
+ return state.staged() ||
+ (state.param_source() == ParamSource::Backend && state.compute_backend == state.params_backend() &&
+ !needs_lora_staging(state) && state.loaded());
+}
+
+const ModelManager::CachedLoraWeight* ModelManager::reusable_lora_weight(const TensorState& state) {
+ auto current = [](const TensorState& tensor) {
+ const auto* cached = tensor.cached_lora().get();
+ return cached && cached->lora_epoch == resource_of(tensor).current_lora_epoch_ &&
+ cached->compute_backend == tensor.compute_backend
+ ? cached
+ : nullptr;
+ };
+ const auto* cached = current(state);
+ if (cached && has_lora_int8_pair(state) && !current(*state.lora_int8_partner)) {
+ return nullptr;
+ }
+ return cached;
+}
+
+bool ModelManager::preserves_batch_merge(TensorState& state) const {
+ return lora_batch_spills_ && lora_batch_spills_->count(&state) &&
+ state.applied_epoch() == resource_of(state).current_lora_epoch_;
+}
+
+bool ModelManager::cache_merged_lora_weights(const ComputeStagingBlock& block) {
+ if (!block.buffer || ggml_backend_buffer_is_host(block.buffer)) {
+ return true;
+ }
+ auto merged_in_block = [&](const TensorState& state) {
+ return state.tensor && !state.tensor->view_src && state.tensor->buffer == block.buffer &&
+ state.storage_epoch() != state.applied_epoch() &&
+ state.applied_epoch() == resource_of(state).current_lora_epoch_;
+ };
+ std::vector<TensorState*> states;
+ for (const auto& [state, _] : block.staged_tensors) {
+ if (!state || !merged_in_block(*state) || reusable_lora_weight(*state))
+ continue;
+ const bool spill = lora_batch_spills_ && lora_batch_spills_->count(state);
+ if (!spill && (lora_batch_spills_ || state->residency_mode == ResidencyMode::Disk))
+ continue;
+ if (has_lora_int8_pair(*state) && !merged_in_block(*state->lora_int8_partner)) {
+ if (spill)
+ return false;
+ continue;
+ }
+ states.push_back(state);
+ }
+ if (states.empty()) {
+ return true;
+ }
+
+ struct HostBlock {
+ BackendBuffer buffer{nullptr, ggml_backend_buffer_free};
+ std::vector<CachedLoraWeight> weights;
+ };
+ auto host = std::make_shared<HostBlock>();
+ host->weights.resize(states.size());
+ HostWeightCopies copies;
+ for (size_t i = 0; i < states.size(); ++i) {
+ auto& weight = host->weights[i];
+ weight.compute_backend = states[i]->compute_backend;
+ weight.lora_epoch = states[i]->applied_epoch();
+ copies.emplace_back(states[i]->tensor, &weight.tensor);
+ }
+ // Pinned like offloaded weights, so segment prefetch uploads the cache asynchronously.
+ auto host_buft = ggml_backend_cpu_buffer_type();
+ if (auto device = ggml_backend_get_device(block.compute_backend); device && !sd_backend_is(block.compute_backend, "Vulkan")) {
+ if (auto pinned = ggml_backend_dev_host_buffer_type(device))
+ host_buft = pinned;
+ }
+ const size_t bytes = weight_copy_bytes(host_buft, copies);
+ size_t available = 0;
+ const bool spill = lora_batch_spills_ != nullptr;
+ // A completed batch needs its merged copy back. Outside the merge, caching is optional.
+ if (bytes == SIZE_MAX || !(spill ? ensure_host_capacity(bytes, {}, true, 0, true)
+ : fits_host_capacity(bytes, true, 0, available)))
+ return !spill;
+ host->buffer = copy_weights(host_buft, block.compute_backend, copies, bytes);
+ if (!host->buffer) {
+ return !spill;
+ }
+ for (size_t i = 0; i < states.size(); ++i) {
+ store_.cache_merged(*states[i], std::shared_ptr<const CachedLoraWeight>(host, &host->weights[i]));
+ }
+ LOG_DEBUG("model manager cached %.2f MiB of merged LoRA weights in RAM", bytes / (1024.0 * 1024.0));
+ return true;
}
-bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorState*>& states) {
+void ModelManager::place_first_loads(const DeviceMemoryRequest& request, const std::vector<TensorState*>& states) {
+ std::vector<TensorState*> candidates;
+ size_t next_use = SIZE_MAX;
+ std::unordered_set<sd::weights::ResourceId> resources;
+ for (auto* state : states) {
+ if (!state || should_ignore(*state) || state->sources.empty() || state->loaded() ||
+ state->staged() || state->param_source() != ParamSource::Backend ||
+ state->residency_mode == ResidencyMode::Disk || state->split_buffer_type || state->tensor->view_src ||
+ state->usage_op == GGML_OP_CUSTOM || has_lora_int8_pair(*state) || needs_lora_staging(*state) ||
+ state->params_backend() != home_backend(*state) || sd_backend_is_cpu(state->params_backend()))
+ continue;
+ candidates.push_back(state);
+ next_use = std::min(next_use, next_weight_use(*state));
+ }
+ if (candidates.empty())
+ return;
+ for (auto* state : states) {
+ if (state)
+ resources.insert(reinterpret_cast<sd::weights::ResourceId>(state->resource));
+ }
+ std::map<ggml_backend_t, std::vector<TensorState*>> by_home;
+ for (auto* state : candidates)
+ by_home[state->params_backend()].push_back(state);
+ const ReclaimScope scope{&resources, next_use};
+ size_t host_left = 0;
+ if (!fits_host_capacity(0, true, 0, host_left))
+ host_left = 0;
+ for (auto& [home, group] : by_home) {
+ const bool compute = ggml_backend_get_device(home) == ggml_backend_get_device(request.compute_backend);
+ // The compute device must also hold the request's runtime buffers and remaining weights.
+ const auto capacity = compute ? check_capacity(request, states, DeviceMemoryCheck::Reclaimable, false, scope)
+ : check_capacity({home, request.owner_id}, group, DeviceMemoryCheck::Reclaimable, false, scope);
+ if (capacity.fits(true))
+ continue;
+ // Placing new weights in their params backend would displace resident weights.
+ // In order, each weight goes to RAM while it has room, otherwise its compute copy reads the model file.
+ for (auto* state : group) {
+ const auto host = next_residency_backend(*state, home);
+ const auto buft = host ? params_buffer_type_for(*state, host) : nullptr;
+ const bool ram = buft && ggml_backend_buft_is_host(buft);
+ const size_t size = ram ? GGML_PAD(ggml_backend_buft_get_alloc_size(buft, state->tensor), ggml_backend_buft_get_alignment(buft)) : 0;
+ // A compute device without support for the weight's op reads it from RAM, as
+ // params_buffer_type_for() would place it, so it cannot read the model file directly.
+ const bool supported = device_supports_param_op(ggml_backend_get_device(state->compute_backend), state->tensor,
+ state->usage_op, ggml_backend_get_default_buffer_type(state->compute_backend));
+ if (ram && (size <= host_left || !supported)) {
+ host_left -= std::min(size, host_left);
+ store_.move_to(*state, host);
+ } else if (!supported) {
+ continue;
+ } else {
+ store_.move_to(*state, state->compute_backend);
+ store_.read_from_file(*state, true);
+ }
+ }
+ LOG_DEBUG("model manager placed %zu new weight tensors below %s to keep resident weights",
+ group.size(), ggml_backend_name(home));
+ }
+}
+
+ggml_backend_t ModelManager::host_backend_for(const TensorState& state) const {
+ if (state.preferred_backend && sd_backend_is_cpu(state.preferred_backend)) {
+ return state.preferred_backend;
+ }
+ if (!host_backend_) {
+ host_backend_.reset(sd_backend_cpu_init());
+ }
+ return host_backend_.get();
+}
+
+bool ModelManager::prefers_compute_residency(const TensorState& state) const {
+ const auto home = home_backend(state);
+ return state.residency_mode != ResidencyMode::Disk &&
+ (!home || !state.compute_backend || ggml_backend_get_device(home) == ggml_backend_get_device(state.compute_backend));
+}
+
+ggml_backend_t ModelManager::next_residency_backend(const TensorState& state, ggml_backend_t from) const {
+ const auto home = home_backend(state);
+ if (!from || !home) {
+ return nullptr;
+ }
+ // params backend -> RAM -> model file
+ std::vector<ggml_backend_t> chain{home};
+ const bool disk = state.residency_mode == ResidencyMode::Disk;
+ // A mapped model file already serves reloads from the page cache.
+ const bool mapped = resource_of(state).enable_mmap_ && state.sources.size() == 1 && state.source_file == 0;
+ if (!disk && !mapped && !sd_backend_is_cpu(home)) {
+ chain.push_back(host_backend_for(state));
+ }
+ const auto device = ggml_backend_get_device(from);
+ for (size_t i = 0; i + 1 < chain.size(); ++i) {
+ const bool same = sd_backend_is_cpu(from) ? sd_backend_is_cpu(chain[i]) : ggml_backend_get_device(chain[i]) == device;
+ if (same) {
+ return chain[i + 1];
+ }
+ }
+ return nullptr;
+}
+
+bool ModelManager::ensure_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,
+ std::string* device_memory_error) {
+ return capacity_provider().reserve(request, required_params, preferred_eviction_order, protected_params, device_memory_error);
+}
+
+bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorState*>& states, bool& capacity_failure) {
std::map<std::tuple<ggml_backend_t, ggml_backend_buffer_type_t, Resource*, ModelLoader::FileId>, std::vector<TensorState*>> states_by_staging_target;
for (TensorState* state : states) {
if (state == nullptr || should_ignore(*state) || (state->sources.empty() && is_optional_missing_tensor(state->name))) {
@@ -739,17 +994,24 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
LOG_ERROR("model manager compute backend is null for tensor '%s'", state->name.c_str());
return false;
}
- if (state->params_backend == nullptr) {
+ if (state->params_backend() == nullptr) {
LOG_ERROR("model manager params backend is null for tensor '%s'", state->name.c_str());
return false;
}
// Custom CPU operators must retain host weights even when the runner uses a GPU.
- if (state->staged_to_compute_backend ||
+ if (state->staged() ||
(!needs_lora_staging(*state) &&
- (state->usage_op == GGML_OP_CUSTOM || state->compute_backend == state->params_backend))) {
+ (state->usage_op == GGML_OP_CUSTOM ||
+ (state->param_source() == ParamSource::Backend && state->compute_backend == state->params_backend())))) {
+ if (!state->staged() && !state->tensor->data) {
+ LOG_ERROR("model manager tensor '%s' is not loaded to params backend", state->name.c_str());
+ return false;
+ }
continue;
}
- if (!state->loaded_to_params_backend || state->tensor == nullptr || state->tensor->data == nullptr) {
+ if (state->tensor == nullptr ||
+ (state->param_source() != ParamSource::ModelFile &&
+ (!state->loaded() || state->tensor->data == nullptr))) {
LOG_ERROR("model manager tensor '%s' is not loaded to params backend", state->name.c_str());
return false;
}
@@ -757,7 +1019,7 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
if (staging_buft == nullptr) {
staging_buft = ggml_backend_get_default_buffer_type(state->compute_backend);
}
- states_by_staging_target[{state->compute_backend, staging_buft, state->resource, state->source_file}].push_back(state);
+ states_by_staging_target[{state->compute_backend, staging_buft, resource_ptr(*state), state->source_file}].push_back(state);
}
for (const auto& pair : states_by_staging_target) {
@@ -782,25 +1044,30 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
if (chunk.empty()) {
return true;
}
- if (retain_weights_ && ggml_backend_buft_is_host(staging_buft) && !ensure_host_capacity(bytes, states)) {
+ if (ggml_backend_buft_is_host(staging_buft) && !ensure_host_capacity(bytes, states)) {
return false;
}
#ifdef _WIN32
// WDDM device allocations also consume the system commit budget.
- if (retain_weights_ && !ggml_backend_buft_is_host(staging_buft) &&
+ if (!ggml_backend_buft_is_host(staging_buft) &&
sd_backend_is(compute_backend, "CUDA") && !ensure_host_capacity(0, states, false, bytes)) {
return false;
}
#endif
- if (retain_weights_ && !ggml_backend_buft_is_host(staging_buft) &&
+ if (!ggml_backend_buft_is_host(staging_buft) &&
(max_vram_.bytes_for_backend(compute_backend) > 0 || std::any_of(chunk.begin(), chunk.end(), [](const auto* state) {
- return needs_lora_staging(*state) && state->params_backend == state->compute_backend;
+ return state->param_source() == ParamSource::ModelFile || needs_lora_staging(*state);
}))) {
std::vector<ggml_tensor*> protected_params;
for (auto* state : states)
protected_params.push_back(state->tensor);
- if (!execution_engine()->ensure_capacity(*this, {compute_backend, 0, bytes}, {}, {}, protected_params))
+ // 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;
return false;
+ }
}
ggml_init_params init_params;
init_params.mem_size = std::max<size_t>(1, chunk.size()) * ggml_tensor_overhead();
@@ -820,32 +1087,53 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
ggml_backend_buffer_t compute_buffer =
ggml_backend_alloc_ctx_tensors_from_buft(staging_ctx, staging_buft);
if (compute_buffer == nullptr) {
+ capacity_failure = !ggml_backend_buft_is_host(staging_buft);
LOG_ERROR("model manager alloc compute params backend buffer failed, num_tensors = %zu",
staged_tensors.size());
ggml_free(staging_ctx);
return false;
}
ggml_backend_buffer_set_usage(compute_buffer, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
+ // Compute copies without a params copy read the model file directly.
+ std::vector<sd::weights::ReadTarget> file_reads;
+ for (auto& [state, staging_tensor] : staged_tensors) {
+ if (state->param_source() == ParamSource::ModelFile && !reusable_lora_weight(*state))
+ file_reads.push_back(read_target(*state, staging_tensor));
+ }
+ if (!file_reads.empty() && !sd::weights::read_weights(file_reads)) {
+ ggml_backend_buffer_free(compute_buffer);
+ ggml_free(staging_ctx);
+ return false;
+ }
+ auto block = std::make_unique<ComputeStagingBlock>();
+ std::vector<uint64_t> epochs;
for (auto& staged_tensor : staged_tensors) {
TensorState* state = staged_tensor.first;
ggml_tensor* managed_tensor = state->tensor;
ggml_tensor* staging_tensor = staged_tensor.second;
- ggml_backend_tensor_copy(managed_tensor, staging_tensor);
+ // The compute copy carries the merge of its source.
+ uint64_t epoch = UINT64_MAX;
+ if (const auto* cached = reusable_lora_weight(*state)) {
+ ggml_backend_tensor_copy(&cached->tensor, staging_tensor);
+ epoch = cached->lora_epoch;
+ } else if (state->param_source() != ParamSource::ModelFile) {
+ ggml_backend_tensor_copy(managed_tensor, staging_tensor);
+ epoch = state->storage_epoch();
+ }
std::swap(managed_tensor->buffer, staging_tensor->buffer);
std::swap(managed_tensor->data, staging_tensor->data);
std::swap(managed_tensor->extra, staging_tensor->extra);
- state->staged_to_compute_backend = true;
+ epochs.push_back(epoch);
}
ggml_backend_synchronize(compute_backend);
- auto block = std::make_unique<ComputeStagingBlock>();
block->compute_backend = compute_backend;
block->buffer = compute_buffer;
block->staging_ctx = staging_ctx;
block->staged_tensors = std::move(staged_tensors);
staged_bytes += ggml_backend_buffer_get_size(compute_buffer);
++staged_blocks;
- compute_staging_blocks_.push_back(std::move(block));
+ store_.add_compute(std::move(block), epochs);
return true;
};
@@ -889,178 +1177,33 @@ bool ModelManager::stage_tensors_to_compute_backend(const std::vector<TensorStat
return true;
}
-bool ModelManager::apply_loras_to_params(const std::vector<TensorState*>& states) {
- std::map<Resource*, std::vector<TensorState*>> groups;
- for (auto* state : states) {
- if (state && !state->resource->loras_.empty() && !state->resource->applying_loras_)
- groups[state->resource].push_back(state);
- }
- for (const auto& [resource, tensors] : groups) {
- if (!apply_resource_loras(*resource, tensors))
- return false;
- }
- return true;
-}
-
-bool ModelManager::apply_resource_loras(Resource& resource, const std::vector<TensorState*>& states) {
- struct ApplyGuard {
- Resource& resource;
- ~ApplyGuard() { resource.applying_loras_ = false; }
- } guard{resource};
- resource.applying_loras_ = true;
-
- struct LoraApplyGroup {
- std::map<std::string, ggml_tensor*> model_tensors;
- std::map<ggml_tensor*, LoraInt8Weight> int8_weights;
- std::vector<TensorState*> states;
- };
-
- using ApplyTarget = std::tuple<ggml_backend_t, ggml_backend_t, ResidencyMode>;
- std::map<ApplyTarget, LoraApplyGroup> groups;
- for (TensorState* state : states) {
- if (state == nullptr || state->tensor == nullptr || state->component == ModelComponent::LoRA ||
- should_ignore(*state) || (state->sources.empty() && is_optional_missing_tensor(state->name))) {
- continue;
- }
- if (needs_lora_staging(*state)) {
- if (!state->staged_to_compute_backend)
- return false;
- } else if (!resource.shared_weights_key_.empty()) {
- continue;
- } else if (state->component == ModelComponent::LatentUpsampler || resource.model_sources_.count(state->source_file) != 0) {
- continue;
- }
- if (state->applied_lora_epoch == resource.current_lora_epoch_) {
- continue;
- }
- if (state->compute_backend == nullptr) {
- LOG_ERROR("model manager compute backend is null for lora target tensor '%s'", state->name.c_str());
- return false;
- }
- if (state->tensor->buffer != nullptr &&
- ggml_backend_buffer_get_type(state->tensor->buffer) == split_buffer_type_for(*state)) {
- if (!resource.warned_split_lora_skip_) {
- LOG_WARN(
- "model manager skipping direct lora application to row-split tensors "
- "(use --lora-apply-mode at_runtime with row split)");
- resource.warned_split_lora_skip_ = true;
- }
- state->applied_lora_epoch = resource.current_lora_epoch_;
- continue;
- }
- if (state->tensor->data == nullptr) {
- LOG_ERROR("model manager lora target tensor '%s' is not prepared", state->name.c_str());
- return false;
- }
- LoraApplyGroup& group = groups[{state->compute_backend, state->params_backend, state->residency_mode}];
- if (state->is_int8_weight) {
- if (resource.lora_targets_.count(state->name) == 0)
- continue;
- if (!state->lora_int8_partner || !state->lora_int8_partner->staged_to_compute_backend) {
- LOG_ERROR("model manager INT8 LoRA target '%s' has no staged weight scale", state->name.c_str());
- return false;
- }
- const auto& storage = state->sources.front();
- group.int8_weights[state->tensor] = {state->lora_int8_partner->tensor, storage.int8_convrot ? storage.int8_convrot_group_size : 0};
- } else if (has_lora_int8_pair(*state)) {
- group.states.push_back(state);
- continue;
- }
- group.model_tensors[state->name] = state->tensor;
- group.states.push_back(state);
- }
-
- if (groups.empty()) {
- return true;
- }
-
- std::set<std::string> all_tensor_names = tensor_names(resource);
- for (auto& group_pair : groups) {
- ggml_backend_t compute_backend = std::get<0>(group_pair.first);
- LoraApplyGroup& group = group_pair.second;
- for (const LoraSpec& lora_spec : resource.loras_) {
- if (group.model_tensors.empty()) {
- continue;
- }
-
- std::string id = lora_id(lora_spec);
- const auto* target = group.states.front();
- auto lora = lora_spec.prepared.lock();
- if (lora && (lora->backend() != compute_backend || lora->params_backend != target->params_backend))
- lora.reset();
- const bool temporary = !lora;
- if (temporary) {
- // The temporary runner is destroyed before this manager call returns.
- auto borrowed_manager = std::shared_ptr<ModelManager>(this, [](ModelManager*) {});
- auto weights = std::make_shared<ResourceHandle>(std::move(borrowed_manager), resource.id);
- lora = std::make_shared<LoraModel>(id, compute_backend, target->params_backend,
- std::move(weights), lora_spec.file_id, resource.lora_version_,
- target->residency_mode);
- }
-
- LoraModel::filter_t lora_tensor_filter = nullptr;
- if (!lora_spec.tensor_name_prefix_filter.empty()) {
- lora_tensor_filter = [&](const std::string& tensor_name) {
- return starts_with(tensor_name, lora_spec.tensor_name_prefix_filter);
- };
- }
- if (temporary && !lora->init_params(resource.n_threads_, lora_tensor_filter)) {
- LOG_WARN("load lora tensors from %s failed", lora_spec.path.c_str());
- if (lora_spec.required) {
- return false;
- }
- continue;
- }
- if (lora->lora_tensors.empty()) {
- if (lora_spec.required) {
- LOG_ERROR("required lora has no tensors: %s", lora_spec.path.c_str());
- return false;
- }
- continue;
- }
- lora->multiplier = lora_spec.multiplier;
- if (!lora->apply(group.model_tensors, all_tensor_names, resource.lora_version_, resource.n_threads_, false, group.int8_weights))
- return false;
- if (temporary)
- lora->release_loaded_tensors();
- else
- lora->runner_end();
- }
-
- for (TensorState* state : group.states) {
- if (state != nullptr) {
- state->applied_lora_epoch = resource.current_lora_epoch_;
- }
- }
- }
- return true;
-}
-
void ModelManager::reset_lora_applied_params(Resource& resource) {
std::unordered_set<TensorState*> affected;
- for (auto& state : tensor_states_) {
- if (state->resource == &resource && state->component != ModelComponent::LoRA && state->applied_lora_epoch != UINT64_MAX) {
+ for (auto& state : store_.tensor_states()) {
+ if (state->resource != &resource || state->component == ModelComponent::LoRA) {
+ continue;
+ }
+ store_.drop_merged_cache(*state);
+ if (state->applied_epoch() != UINT64_MAX) {
affected.insert(state.get());
}
}
if (!resource.shared_weights_key_.empty()) {
- for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end();) {
- if (std::any_of((*it)->staged_tensors.begin(), (*it)->staged_tensors.end(), [&](const auto& item) {
- return affected.count(item.first) != 0;
- })) {
- free_compute_staging_block(**it);
- it = compute_staging_blocks_.erase(it);
- } else {
- ++it;
- }
- }
+ std::vector<ComputeStagingBlock*> stale;
+ for (const auto& block : store_.compute_blocks()) {
+ if (std::any_of(block->staged_tensors.begin(), block->staged_tensors.end(),
+ [&](const auto& item) { return affected.count(item.first) != 0; }))
+ stale.push_back(block.get());
+ }
+ for (auto* block : stale)
+ store_.release_compute(block);
} else {
invalidate_sources(affected);
}
}
bool ModelManager::should_ignore(const TensorState& state) const {
- if (state.resource != &default_resource_ || state.resource->model_sources_.count(state.source_file) != 0) {
+ if (state.resource != &default_resource_ || resource_of(state).model_sources_.count(state.source_file) != 0) {
return false;
}
for (const auto& ignore_prefix : common_ignore_tensors_) {
@@ -1138,10 +1281,10 @@ bool ModelManager::mmap_params(const std::vector<TensorState*>& states,
continue;
}
ggml_backend_dev_t device = nullptr;
- if (!sd_backend_is_cpu(state->compute_backend) && !sd_backend_is_cpu(state->params_backend)) {
+ if (!sd_backend_is_cpu(state->compute_backend) && !sd_backend_is_cpu(state->params_backend())) {
device = ggml_backend_get_device(state->compute_backend);
}
- MmapGroup& group = groups[{state->resource, device}];
+ MmapGroup& group = groups[{resource_ptr(*state), device}];
group.candidates[state->name] = state->tensor;
group.states[state->name] = state;
}
@@ -1153,7 +1296,7 @@ bool ModelManager::mmap_params(const std::vector<TensorState*>& states,
if (device != nullptr && resource->writable_mmap_) {
continue;
}
- auto mmap_store = resource->model_loader_.mmap_tensors(group.candidates, {}, resource->writable_mmap_, device);
+ auto mmap_store = sd::weights::map_weights(resource->model_loader_, group.candidates, resource->writable_mmap_, device);
if (mmap_store.empty()) {
continue;
}
@@ -1169,7 +1312,7 @@ bool ModelManager::mmap_params(const std::vector<TensorState*>& states,
}
if (!block->states.empty()) {
- params_storage_blocks_.push_back(std::move(block));
+ store_.add_storage(std::move(block));
created_storage_blocks.push_back(raw);
}
}
@@ -1177,36 +1320,48 @@ bool ModelManager::mmap_params(const std::vector<TensorState*>& states,
}
bool ModelManager::can_mmap_storage(const TensorState& state) const {
- if (state.sources.size() > 1 || state.source_file != 0 || !state.resource->enable_mmap_ || state.residency_mode != ResidencyMode::ParamBackend) {
+ if (state.sources.size() > 1 || state.source_file != 0 || !resource_of(state).enable_mmap_ || state.residency_mode != ResidencyMode::ParamBackend) {
return false;
}
- if (state.compute_backend == nullptr || state.params_backend == nullptr) {
+ if (state.compute_backend == nullptr || state.params_backend() == nullptr) {
return false;
}
- if (max_ram_bytes_ != 0 && state.resource->writable_mmap_) {
+ if (max_ram_bytes_ != 0 && resource_of(state).writable_mmap_) {
return false;
}
return sd_backend_is_cpu(state.compute_backend) ||
- sd_backend_is_cpu(state.params_backend) ||
+ sd_backend_is_cpu(state.params_backend()) ||
backend_supports_host_buffer(state.compute_backend);
}
+size_t ModelManager::cached_lora_bytes() const {
+ std::unordered_set<ggml_backend_buffer_t> buffers;
+ size_t bytes = 0;
+ for (const auto& state : store_.tensor_states()) {
+ if (state->cached_lora() && buffers.insert(state->cached_lora()->tensor.buffer).second) {
+ const auto size = ggml_backend_buffer_get_size(state->cached_lora()->tensor.buffer);
+ bytes += std::min(size, SIZE_MAX - bytes);
+ }
+ }
+ return bytes;
+}
+
size_t ModelManager::host_weight_bytes() const {
- size_t bytes = 0;
+ size_t bytes = cached_lora_bytes();
auto add = [&](size_t size) { bytes += std::min(size, SIZE_MAX - bytes); };
auto add_buffer = [&](ggml_backend_buffer_t buffer) {
if (buffer && ggml_backend_buffer_is_host(buffer))
add(ggml_backend_buffer_get_size(buffer));
};
- for (const auto& block : params_storage_blocks_) {
+ for (const auto& block : store_.storage_blocks()) {
add_buffer(block->buffer);
// Private writable mappings can hold anonymous pages after merging a LoRA.
- if (!block->mmap_tensor_stores.empty() && block->states.front()->resource->writable_mmap_) {
+ if (!block->mmap_tensor_stores.empty() && resource_of(*block->states.front()).writable_mmap_) {
for (auto* state : block->states)
add(ggml_nbytes(state->tensor));
}
}
- for (const auto& block : compute_staging_blocks_)
+ for (const auto& block : store_.compute_blocks())
add_buffer(block->buffer);
for (const auto& entry : prefetch_blocks_) {
for (const auto& block : entry.second->staging_blocks)
@@ -1215,127 +1370,36 @@ size_t ModelManager::host_weight_bytes() const {
return bytes;
}
-bool ModelManager::evict_host_weight_block(const std::unordered_set<TensorState*>& protected_states) {
- auto idle = [&](TensorState* state) {
- return state->pin_count == 0 && !protected_states.count(state);
- };
- std::map<TensorState*, ComputeStagingBlock*> staging_for_tensor;
- auto staging_idle = [&](const ComputeStagingBlock& block) {
- return std::all_of(block.staged_tensors.begin(), block.staged_tensors.end(),
- [&](const auto& entry) { return idle(entry.first); });
- };
- size_t farthest = 0;
- uint64_t oldest = UINT64_MAX;
- ParamsStorageBlock* storage = nullptr;
- ComputeStagingBlock* staging = nullptr;
- bool prefer_staged = false;
- auto better = [&](size_t next, uint64_t last, bool shared) {
- return next > farthest || (next == farthest &&
- ((shared && !prefer_staged) || (shared == prefer_staged && last < oldest)));
- };
- for (const auto& block : compute_staging_blocks_) {
- uint64_t last_use = 0;
- size_t next_use = planned_next_use_.empty() ? 0 : SIZE_MAX;
- for (const auto& entry : block->staged_tensors) {
- auto* state = entry.first;
- staging_for_tensor.emplace(state, block.get());
- last_use = std::max(last_use, state->last_use_epoch);
- next_use = std::min(next_use, next_weight_use(*state));
- }
- const bool shared = std::any_of(block->staged_tensors.begin(), block->staged_tensors.end(), [](const auto& entry) {
- return !entry.first->resource->shared_weights_key_.empty();
- });
- if (better(next_use, last_use, shared) &&
- ggml_backend_buffer_is_host(block->buffer) && staging_idle(*block)) {
- farthest = next_use;
- oldest = last_use;
- staging = block.get();
- prefer_staged = shared;
- }
+bool ModelManager::fits_host_capacity(size_t pending, bool weight_allocation, size_t pending_device_commit, size_t& available) const {
+ constexpr size_t headroom = 1024ULL * 1024 * 1024;
+ const size_t resident = max_ram_bytes_ ? host_weight_bytes() : 0;
+ available = weight_allocation && max_ram_bytes_ ? max_ram_bytes_ - std::min(max_ram_bytes_, resident) : SIZE_MAX;
+ const int64_t free_ram = sd::backend_fit::available_ram_bytes();
+ if (free_ram >= 0) {
+ const auto free_bytes = static_cast<uint64_t>(free_ram);
+ available = static_cast<size_t>(std::min<uint64_t>(
+ available, free_bytes > headroom ? free_bytes - headroom : 0));
+ if (free_bytes < headroom)
+ return false;
}
-
- std::unordered_set<ComputeStagingBlock*> dependent_staging;
- for (const auto& block : params_storage_blocks_) {
- if (!block->buffer || !ggml_backend_buffer_is_host(block->buffer))
- continue;
- uint64_t last_use = 0;
- size_t next_use = planned_next_use_.empty() ? 0 : SIZE_MAX;
- std::unordered_set<ComputeStagingBlock*> dependencies;
- const bool reclaimable = std::all_of(block->states.begin(), block->states.end(), [&](TensorState* state) {
- if (!idle(state) || state->sources.empty() || state->applied_lora_epoch != UINT64_MAX ||
- state->tensor->view_src != nullptr)
+ if (pending_device_commit > 0) {
+ const int64_t free_commit = sd::backend_fit::available_commit_bytes();
+ if (free_commit >= 0) {
+ const auto free_bytes = static_cast<uint64_t>(free_commit);
+ const auto reserve = pending_device_commit + std::min(headroom, SIZE_MAX - pending_device_commit);
+ if (free_bytes < reserve) {
+ available = 0;
return false;
- last_use = std::max(last_use, state->last_use_epoch);
- next_use = std::min(next_use, next_weight_use(*state));
- if (state->staged_to_compute_backend) {
- auto it = staging_for_tensor.find(state);
- if (it == staging_for_tensor.end())
- return false;
- dependencies.insert(it->second);
}
- return true;
- });
- if (reclaimable && better(next_use, last_use, false) &&
- std::all_of(dependencies.begin(), dependencies.end(), [&](const auto* block) { return staging_idle(*block); })) {
- farthest = next_use;
- oldest = last_use;
- storage = block.get();
- prefer_staged = false;
- dependent_staging = std::move(dependencies);
+ available = std::min(available, static_cast<size_t>(free_bytes - reserve));
}
}
- if (!storage && !staging)
- return false;
- if (!storage)
- dependent_staging.insert(staging);
- for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end();) {
- if (dependent_staging.count(it->get())) {
- LOG_VERBOSE("model manager evicted %.2f MiB of staged weights on %s for RAM",
- ggml_backend_buffer_get_size((*it)->buffer) / (1024.0 * 1024.0),
- ggml_backend_name((*it)->compute_backend));
- free_compute_staging_block(**it);
- it = compute_staging_blocks_.erase(it);
- } else {
- ++it;
- }
- }
- if (storage) {
- LOG_VERBOSE("model manager evicted %.2f MiB of weight storage from RAM",
- ggml_backend_buffer_get_size(storage->buffer) / (1024.0 * 1024.0));
- free_params_storage_block(*storage);
- erase_params_storage_block(storage);
- }
- return true;
+ return pending <= available && (!max_ram_bytes_ || resident <= max_ram_bytes_);
}
-bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation, size_t pending_device_commit) {
- constexpr size_t headroom = 1024ULL * 1024 * 1024;
- size_t available = 0;
- auto fits = [&] {
- const size_t resident = max_ram_bytes_ ? host_weight_bytes() : 0;
- available = weight_allocation && max_ram_bytes_ ? max_ram_bytes_ - std::min(max_ram_bytes_, resident) : SIZE_MAX;
- const int64_t free_ram = sd::backend_fit::available_ram_bytes();
- if (free_ram >= 0) {
- const auto free_bytes = static_cast<uint64_t>(free_ram);
- available = static_cast<size_t>(std::min<uint64_t>(
- available, free_bytes > headroom ? free_bytes - headroom : 0));
- if (free_bytes < headroom)
- return false;
- }
- if (pending_device_commit > 0) {
- const int64_t free_commit = sd::backend_fit::available_commit_bytes();
- if (free_commit >= 0) {
- const auto free_bytes = static_cast<uint64_t>(free_commit);
- const auto reserve = pending_device_commit + std::min(headroom, SIZE_MAX - pending_device_commit);
- if (free_bytes < reserve) {
- available = 0;
- return false;
- }
- available = std::min(available, static_cast<size_t>(free_bytes - reserve));
- }
- }
- return pending <= available && (!max_ram_bytes_ || resident <= max_ram_bytes_);
- };
+bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation, size_t pending_device_commit, bool optional, const sd::weights::PriorityLimit* limit) {
+ size_t available = 0;
+ auto fits = [&] { return fits_host_capacity(pending, weight_allocation, pending_device_commit, available); };
host_memory_error_.clear();
if (fits())
return true;
@@ -1343,11 +1407,15 @@ bool ModelManager::ensure_host_capacity(size_t pending, const std::vector<Tensor
if (!weight_allocation || !max_ram_bytes_ || pending <= max_ram_bytes_) {
std::unordered_set<TensorState*> protected_states(required_states.begin(), required_states.end());
protect_prefetched_states(protected_states);
- while (evict_host_weight_block(protected_states) || (evict_idle_resource_ && evict_idle_resource_())) {
+ while (evict_host_weight_block(protected_states, limit) ||
+ (!optional && evict_idle_resource_ && evict_idle_resource_())) {
if (fits())
return true;
}
}
+ if (optional) {
+ return false;
+ }
const size_t resident = host_weight_bytes();
host_memory_error_ = std::string(weight_allocation ? "RAM weight capacity exceeded. Requested " : "RAM graph capacity exceeded. Requested ") + std::to_string(pending) +
" bytes, " + std::to_string(available) + " bytes available, " +
@@ -1376,9 +1444,13 @@ bool ModelManager::ensure_host_memory(size_t pending, const std::vector<ggml_ten
bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
const std::vector<TensorState*>& required_states,
- std::vector<ParamsStorageBlock*>& created_storage_blocks) {
- std::map<std::tuple<ggml_backend_buffer_type_t, int, Resource*, ModelLoader::FileId>, std::vector<TensorState*>> states_by_buffer_type;
+ std::vector<ParamsStorageBlock*>& created_storage_blocks,
+ bool* capacity_failure) {
+ // Originals of merged weights get blocks of their own: once merged, compute reads only their
+ // merged copies, so reclaim can release the whole block without touching weights still read in place.
+ std::map<std::tuple<ggml_backend_buffer_type_t, int, Resource*, ModelLoader::FileId, bool>, std::vector<TensorState*>> states_by_buffer_type;
std::vector<ggml_tensor*> protected_params;
+ std::vector<std::pair<TensorState*, size_t>> host_weights;
size_t host_bytes = 0;
for (TensorState* state : states) {
if (state == nullptr || state->tensor == nullptr) {
@@ -1388,21 +1460,65 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
if (params_buft == nullptr) {
return false;
}
- if (retain_weights_ && ggml_backend_buft_is_host(params_buft)) {
+ if (ggml_backend_buft_is_host(params_buft)) {
const size_t bytes = GGML_PAD(ggml_backend_buft_get_alloc_size(params_buft, state->tensor),
ggml_backend_buft_get_alignment(params_buft));
host_bytes += std::min(bytes, SIZE_MAX - host_bytes);
+ host_weights.emplace_back(state, bytes);
}
- states_by_buffer_type[{params_buft, static_cast<int>(state->residency_mode), state->resource, state->source_file}].push_back(state);
+ states_by_buffer_type[{params_buft, static_cast<int>(state->residency_mode), resource_ptr(*state), state->source_file,
+ needs_lora_staging(*state)}]
+ .push_back(state);
}
- if (host_bytes > 0 && !ensure_host_capacity(host_bytes, required_states))
- return false;
- if (retain_weights_) {
+ size_t host_left = 0;
+ if (host_bytes > 0 && !fits_host_capacity(host_bytes, true, 0, host_left)) {
+ // Reserve RAM for tensors the compute device cannot read directly from a device buffer.
+ std::unordered_set<const ggml_tensor*> view_bases;
for (auto* state : required_states) {
- if (state)
- protected_params.push_back(state->tensor);
+ for (auto* source = state && state->tensor ? state->tensor->view_src : nullptr; source; source = source->view_src)
+ view_bases.insert(source);
+ }
+ std::vector<std::pair<TensorState*, size_t>> file_candidates;
+ host_bytes = 0;
+ for (const auto& [state, bytes] : host_weights) {
+ auto compute = state->compute_backend;
+ if (sd_backend_is_cpu(state->params_backend()) && compute && !sd_backend_is_cpu(compute) &&
+ !state->sources.empty() && !state->split_buffer_type && state->usage_op != GGML_OP_CUSTOM &&
+ !view_bases.count(state->tensor)) {
+ const auto buft = ggml_backend_get_default_buffer_type(compute);
+ if (buft && !ggml_backend_buft_is_host(buft) &&
+ device_supports_param_op(ggml_backend_get_device(compute), state->tensor, state->usage_op, buft)) {
+ file_candidates.emplace_back(state, bytes);
+ continue;
+ }
+ }
+ host_bytes += std::min(bytes, SIZE_MAX - host_bytes);
+ }
+ host_left -= std::min(host_left, host_bytes);
+ for (const auto& [state, bytes] : file_candidates) {
+ if (bytes <= host_left) {
+ host_bytes += bytes;
+ host_left -= bytes;
+ } else {
+ store_.move_to(*state, state->compute_backend);
+ store_.read_from_file(*state, true);
+ }
+ }
+ for (auto& [key, group] : states_by_buffer_type) {
+ if (ggml_backend_buft_is_host(std::get<0>(key))) {
+ group.erase(std::remove_if(group.begin(), group.end(), [](const auto* state) {
+ return state->param_source() == ParamSource::ModelFile;
+ }),
+ group.end());
+ }
}
}
+ if (host_bytes > 0 && !ensure_host_capacity(host_bytes, required_states))
+ return false;
+ for (auto* state : required_states) {
+ if (state)
+ protected_params.push_back(state->tensor);
+ }
for (const auto& pair : states_by_buffer_type) {
ggml_backend_buffer_type_t params_buft = std::get<0>(pair.first);
@@ -1420,10 +1536,10 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
}
std::unique_ptr<ggml_backend_buffer, decltype(&ggml_backend_buffer_free)> cached_buffer(nullptr, ggml_backend_buffer_free);
- if (retain_weights_ && !ggml_backend_buft_is_host(params_buft)) {
+ if (!ggml_backend_buft_is_host(params_buft)) {
const auto* state = chunk.front();
- auto backend = state->residency_mode == ResidencyMode::Disk ? state->compute_backend : state->params_backend;
- const auto& placements = state->resource->split_buffer_limits_;
+ auto backend = state->params_backend();
+ const auto& placements = resource_of(*state).split_buffer_limits_;
auto placement = placements.find(params_buft);
const auto devices = placement == placements.end()
? std::vector<std::pair<ggml_backend_t, size_t>>{{backend, 0}}
@@ -1434,9 +1550,15 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
}
const size_t reused_bytes = cached_buffer ? chunk_size : 0;
for (const auto& [device, limit] : devices) {
- if (device && !execution_engine()->ensure_capacity(
- *this, {device, 0, chunk_size, 0, limit, reused_bytes}, {}, {}, protected_params)) {
- LOG_ERROR("model manager cannot fit params buffer on %s", ggml_backend_name(device));
+ 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) {
+ *capacity_failure = true;
+ LOG_INFO("model manager cannot fit params buffer on %s", ggml_backend_name(device));
+ } else {
+ LOG_ERROR("model manager cannot fit params buffer on %s", ggml_backend_name(device));
+ }
return false;
}
}
@@ -1449,6 +1571,8 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
if (buffer == nullptr) {
LOG_ERROR("model manager alloc params backend buffer failed, size = %.2fMB",
chunk_size / (1024.0 * 1024.0));
+ if (capacity_failure && !ggml_backend_buft_is_host(params_buft))
+ *capacity_failure = true;
return false;
}
ggml_backend_buffer_set_usage(buffer, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
@@ -1479,12 +1603,10 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
offset += tensor_size;
}
- auto block = std::make_unique<ParamsStorageBlock>();
- block->buffer = buffer;
- block->states = chunk;
- ParamsStorageBlock* raw = block.get();
- params_storage_blocks_.push_back(std::move(block));
- created_storage_blocks.push_back(raw);
+ auto block = std::make_unique<ParamsStorageBlock>();
+ block->buffer = buffer;
+ block->states = chunk;
+ created_storage_blocks.push_back(store_.add_storage(std::move(block)));
return true;
};
@@ -1515,177 +1637,56 @@ bool ModelManager::alloc_params_buffers(const std::vector<TensorState*>& states,
return true;
}
-bool ModelManager::load_tensor_parts(TensorState& state) {
- auto ctx = std::unique_ptr<ggml_context, decltype(&ggml_free)>(
- ggml_init({state.sources.size() * ggml_tensor_overhead(), nullptr, true}), ggml_free);
- if (!ctx) {
- return false;
- }
- const size_t size = ggml_nbytes(state.tensor);
- std::vector<uint8_t> buffer;
- void* data = state.tensor->data;
- if (!ggml_backend_buffer_is_host(state.tensor->buffer)) {
- buffer.resize(size);
- data = buffer.data();
- }
- std::map<std::string, ggml_tensor*> parts;
- std::set<std::string> names;
- size_t offset = 0;
- for (const auto& source : state.sources) {
- auto part = ggml_new_tensor(ctx.get(), state.tensor->type, source.n_dims, source.ne);
- const size_t part_size = ggml_nbytes(part);
- if (part_size > size - offset) {
- return false;
- }
- part->data = static_cast<uint8_t*>(data) + offset;
- parts[source.name] = part;
- names.insert(source.name);
- offset += part_size;
- }
- if (offset != size) {
- return false;
- }
- std::set<std::string> loaded;
- std::mutex mutex;
- auto callback = [&](const TensorStorage& source, ggml_tensor** dst) {
- *dst = nullptr;
- auto part = parts.find(source.name);
- if (part != parts.end()) {
- *dst = part->second;
- std::lock_guard<std::mutex> lock(mutex);
- loaded.insert(source.name);
- }
- return true;
- };
- auto& resource = *state.resource;
- const bool success = state.source_file == 0
- ? resource.model_loader_.load_tensors(callback, resource.enable_mmap_, &names, false)
- : source_loader(resource, state.source_file).load_file_tensors(state.source_file, state.source_version, callback, names, resource.enable_mmap_);
- if (!success || loaded != names) {
- return false;
- }
- if (!buffer.empty()) {
- // Upload the assembled tensor once, including for row-split backend buffers.
- ggml_backend_tensor_set(state.tensor, buffer.data(), 0, size);
- }
- state.loaded_to_params_backend = true;
- return true;
+sd::weights::ReadTarget ModelManager::read_target(const TensorState& state, ggml_tensor* destination) {
+ auto& resource = resource_of(state);
+ auto source = resource.model_sources_.find(state.source_file);
+ sd::weights::ReadTarget target;
+ target.loader = source == resource.model_sources_.end() ? &resource.model_loader_ : &source->second;
+ target.file = state.source_file;
+ target.version = state.source_version;
+ target.use_mmap = resource.enable_mmap_;
+ target.name = state.name;
+ target.sources = &state.sources;
+ target.destination = destination;
+ return target;
}
bool ModelManager::load_tensors(const std::vector<TensorState*>& states) {
- using ReadGroup = std::tuple<Resource*, ModelLoader::FileId, SDVersion>;
- using ReadBatch = std::map<std::string, std::vector<ggml_tensor*>>;
- std::map<ReadGroup, std::vector<ReadBatch>> groups;
- size_t part_count = 0;
- for (const auto* state : states) {
- if (state != nullptr && state->sources.size() > 1 && ggml_backend_buffer_is_host(state->tensor->buffer)) {
- part_count += state->sources.size();
- }
- }
- auto parts_ctx = std::unique_ptr<ggml_context, decltype(&ggml_free)>(
- part_count > 0 ? ggml_init({part_count * ggml_tensor_overhead(), nullptr, true}) : nullptr, ggml_free);
- if (part_count > 0 && !parts_ctx) {
- return false;
- }
- auto add_destination = [&](const TensorState& state, const std::string& name, ggml_tensor* tensor) {
- auto& batches = groups[{state.resource, state.source_file, state.source_version}];
- // The loader supplies one destination per name; incompatible destinations need another batch.
- auto batch = std::find_if(batches.begin(), batches.end(), [&](const ReadBatch& candidate) {
- auto found = candidate.find(name);
- return found == candidate.end() ||
- (found->second.front()->type == tensor->type && ggml_are_same_shape(found->second.front(), tensor));
- });
- if (batch == batches.end()) {
- batches.emplace_back();
- batch = std::prev(batches.end());
- }
- (*batch)[name].push_back(tensor);
- };
- for (auto* state : states) {
- if (state == nullptr)
- continue;
- if (state->sources.size() > 1) {
- if (ggml_backend_buffer_is_host(state->tensor->buffer)) {
- const size_t size = ggml_nbytes(state->tensor);
- size_t offset = 0;
- for (const auto& source : state->sources) {
- auto* part = ggml_new_tensor(parts_ctx.get(), state->tensor->type, source.n_dims, source.ne);
- const size_t part_size = ggml_nbytes(part);
- if (part_size > size - offset) {
- return false;
- }
- part->data = static_cast<uint8_t*>(state->tensor->data) + offset;
- part->buffer = state->tensor->buffer;
- add_destination(*state, source.name, part);
- offset += part_size;
- }
- if (offset != size) {
- return false;
- }
- } else if (!load_tensor_parts(*state)) {
- return false;
- }
- continue;
- }
- add_destination(*state, state->name, state->tensor);
- }
- for (auto& group : groups) {
- for (auto& batch : group.second) {
- std::set<std::string> names;
- std::set<std::string> loaded;
- std::mutex mutex;
- for (const auto& entry : batch)
- names.insert(entry.first);
- auto callback = [&](const TensorStorage& source, ggml_tensor** dst) {
- *dst = nullptr;
- auto found = batch.find(source.name);
- if (found == batch.end())
- return true;
- *dst = found->second.front();
- std::lock_guard<std::mutex> lock(mutex);
- loaded.insert(source.name);
- return true;
- };
- const auto [resource, file, version] = group.first;
- bool success = file == 0 ? resource->model_loader_.load_tensors(callback, resource->enable_mmap_, &names)
- : source_loader(*resource, file).load_file_tensors(file, version, callback, names, resource->enable_mmap_);
- if (!success || loaded != names)
- return false;
- for (auto& entry : batch) {
- auto* first = entry.second.front();
- for (auto* tensor : entry.second) {
- if (tensor != first)
- ggml_backend_tensor_copy(first, tensor);
- }
- }
- }
- }
+ std::vector<sd::weights::ReadTarget> targets;
+ targets.reserve(states.size());
for (auto* state : states) {
if (state != nullptr)
- state->loaded_to_params_backend = true;
+ targets.push_back(read_target(*state, state->tensor));
}
+ if (!sd::weights::read_weights(targets))
+ return false;
+ store_.bind_loaded(states);
return true;
}
ggml_backend_buffer_type_t ModelManager::params_buffer_type_for(const TensorState& state) const {
- if (state.params_backend == nullptr) {
+ return params_buffer_type_for(state, state.params_backend());
+}
+
+ggml_backend_buffer_type_t ModelManager::params_buffer_type_for(const TensorState& state, ggml_backend_t params_backend) const {
+ if (params_backend == nullptr) {
LOG_ERROR("model manager params backend is null for tensor '%s'", state.name.c_str());
return nullptr;
}
ggml_backend_buffer_type_t params_buft = nullptr;
- if (state.compute_backend != nullptr && state.params_backend != state.compute_backend &&
- sd_backend_is_cpu(state.params_backend)) {
+ if (state.compute_backend != nullptr && params_backend != state.compute_backend &&
+ sd_backend_is_cpu(params_backend)) {
// Vulkan host buffers are driver allocations. Keeping offloaded weights in them
// can exhaust Vulkan memory even after their device copies have been evicted.
ggml_backend_dev_t compute_dev = ggml_backend_get_device(state.compute_backend);
if (compute_dev != nullptr && !sd_backend_is(state.compute_backend, "Vulkan")) {
params_buft = ggml_backend_dev_host_buffer_type(compute_dev);
}
- } else if (state.params_backend == state.compute_backend) {
+ } else if (params_backend == state.compute_backend) {
params_buft = split_buffer_type_for(state);
}
if (params_buft == nullptr) {
- params_buft = ggml_backend_get_default_buffer_type(state.params_backend);
+ params_buft = ggml_backend_get_default_buffer_type(params_backend);
}
if (state.usage_op != GGML_OP_NONE &&
state.compute_backend != nullptr) {
@@ -1706,189 +1707,21 @@ ggml_backend_buffer_type_t ModelManager::params_buffer_type_for(const TensorStat
return params_buft;
}
-void ModelManager::free_compute_staging_block(ComputeStagingBlock& block) {
- for (auto& staged_tensor : block.staged_tensors) {
- TensorState* state = staged_tensor.first;
- ggml_tensor* staging_tensor = staged_tensor.second;
- if (state == nullptr || state->tensor == nullptr || staging_tensor == nullptr) {
- continue;
- }
- ggml_tensor* managed_tensor = state->tensor;
- managed_tensor->buffer = staging_tensor->buffer;
- managed_tensor->data = staging_tensor->data;
- managed_tensor->extra = staging_tensor->extra;
- staging_tensor->buffer = nullptr;
- staging_tensor->data = nullptr;
- staging_tensor->extra = nullptr;
-
- state->staged_to_compute_backend = false;
- state->applied_lora_epoch = UINT64_MAX;
- }
-
- if (block.buffer != nullptr) {
- ggml_backend_buffer_free(block.buffer);
- block.buffer = nullptr;
- }
- if (block.staging_ctx != nullptr) {
- ggml_free(block.staging_ctx);
- block.staging_ctx = nullptr;
- }
- block.staged_tensors.clear();
-}
-
void ModelManager::protect_prefetched_states(std::unordered_set<TensorState*>& states) const {
for (const auto& entry : prefetch_blocks_)
states.insert(entry.second->states.begin(), entry.second->states.end());
}
-void ModelManager::release_idle_gpu_staging() {
- std::unordered_set<TensorState*> protected_states;
- protect_prefetched_states(protected_states);
- std::unordered_set<TensorState*> target_states;
- for (const auto& block : compute_staging_blocks_) {
- if (!block->buffer || ggml_backend_buffer_is_host(block->buffer))
- continue;
- // Staging swaps the original storage into the block's tensor metadata.
- for (const auto& [state, original] : block->staged_tensors) {
- if (state && state->loaded_to_params_backend && original && original->data && original->buffer &&
- ggml_backend_buffer_is_host(original->buffer) && !protected_states.count(state))
- target_states.insert(state);
- }
- }
- if (!target_states.empty())
- release_compute_staging_blocks(false, &target_states);
-}
-
-void ModelManager::release_compute_staging_blocks(bool force,
- const std::unordered_set<TensorState*>* target_states) {
- struct ReleaseStats {
- size_t bytes = 0;
- size_t tensors = 0;
- size_t blocks = 0;
- };
- std::map<ggml_backend_t, ReleaseStats> released;
- for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end();) {
- ComputeStagingBlock* block = it->get();
- bool can_release = force;
- if (!can_release) {
- can_release = std::all_of(block->staged_tensors.begin(),
- block->staged_tensors.end(),
- [target_states](const std::pair<TensorState*, ggml_tensor*>& pair) {
- TensorState* state = pair.first;
- if (state == nullptr) {
- return true;
- }
- if (target_states != nullptr &&
- target_states->find(state) == target_states->end()) {
- return false;
- }
- return state->pin_count == 0;
- });
- }
-
- if (can_release) {
- if (block->buffer != nullptr) {
- auto& stats = released[block->compute_backend];
- stats.bytes += ggml_backend_buffer_get_size(block->buffer);
- stats.tensors += block->staged_tensors.size();
- ++stats.blocks;
- }
- free_compute_staging_block(*block);
- it = compute_staging_blocks_.erase(it);
- } else {
- ++it;
- }
- }
- for (const auto& entry : released) {
- LOG_DEBUG("model manager released compute params (%6.2f MB, %zu tensors, %zu blocks) from %s",
- entry.second.bytes / (1024.f * 1024.f),
- entry.second.tensors, entry.second.blocks,
- entry.first != nullptr ? ggml_backend_name(entry.first) : "unknown");
- }
-}
-
-void ModelManager::free_params_storage_block(ParamsStorageBlock& block) {
- if (block.buffer != nullptr) {
- LOG_DEBUG("free params buffer: %.2f MB(%s), %zu tensors on %s",
- ggml_backend_buffer_get_size(block.buffer) / (1024.0 * 1024.0),
- ggml_backend_buffer_is_host(block.buffer) ? "RAM" : "VRAM",
- block.states.size(), ggml_backend_buffer_name(block.buffer));
- ggml_backend_buffer_free(block.buffer);
- block.buffer = nullptr;
- }
- block.mmap_tensor_stores.clear();
-
- for (TensorState* state : block.states) {
- if (state == nullptr || state->tensor == nullptr) {
- continue;
- }
- state->tensor->buffer = nullptr;
- state->tensor->data = nullptr;
- state->tensor->extra = nullptr;
-
- state->loaded_to_params_backend = false;
- state->applied_lora_epoch = UINT64_MAX;
- }
- block.states.clear();
-}
-
-void ModelManager::release_params_storage_blocks(bool force,
- const std::unordered_set<TensorState*>* target_states) {
- for (auto it = params_storage_blocks_.begin(); it != params_storage_blocks_.end();) {
- ParamsStorageBlock* block = it->get();
- bool can_release = force;
- if (!can_release) {
- can_release = std::all_of(block->states.begin(),
- block->states.end(),
- [target_states](TensorState* state) {
- if (state == nullptr) {
- return true;
- }
- if (target_states != nullptr &&
- target_states->find(state) == target_states->end()) {
- return false;
- }
- return state->pin_count == 0 &&
- !state->staged_to_compute_backend &&
- state->residency_mode == ResidencyMode::Disk;
- });
- }
-
- if (can_release) {
- free_params_storage_block(*block);
- it = params_storage_blocks_.erase(it);
- } else {
- ++it;
- }
- }
-}
-
-void ModelManager::erase_params_storage_block(ParamsStorageBlock* block) {
- auto it = std::find_if(params_storage_blocks_.begin(),
- params_storage_blocks_.end(),
- [block](const std::unique_ptr<ParamsStorageBlock>& item) {
- return item.get() == block;
- });
- if (it != params_storage_blocks_.end()) {
- params_storage_blocks_.erase(it);
- }
-}
-
void ModelManager::release_all() {
clear_all_prefetched_params();
runtime_residencies_.clear();
runtime_owners_.clear();
- for (auto& state : tensor_states_) {
- state->pin_count = 0;
- state->applied_lora_epoch = UINT64_MAX;
- }
- release_compute_staging_blocks(true);
- release_params_storage_blocks(true);
+ store_.release_all();
}
ggml_tensor* ModelManager::resolve_param_tensor(ggml_tensor* tensor) const {
for (auto* current = tensor; current != nullptr; current = current->view_src) {
- if (tensor_states_by_tensor_.count(current) != 0)
+ if (store_.tensor_index().count(current) != 0)
return current;
}
return nullptr;
@@ -1923,13 +1756,13 @@ bool ModelManager::resolve_required_tensor_states(const std::vector<ggml_tensor*
if (tensor == nullptr) {
continue;
}
- auto found = tensor_states_by_tensor_.find(tensor);
+ auto found = store_.tensor_index().find(tensor);
// Unregistered views can be rebound without changing the parameter list.
- cacheable &= found != tensor_states_by_tensor_.end();
- for (auto view = tensor->view_src; found == tensor_states_by_tensor_.end() && view != nullptr; view = view->view_src) {
- found = tensor_states_by_tensor_.find(view);
+ cacheable &= found != store_.tensor_index().end();
+ for (auto view = tensor->view_src; found == store_.tensor_index().end() && view != nullptr; view = view->view_src) {
+ found = store_.tensor_index().find(view);
}
- if (found == tensor_states_by_tensor_.end()) {
+ if (found == store_.tensor_index().end()) {
LOG_ERROR("model manager tensor '%s' is not registered", ggml_get_name(tensor));
return false;
}
@@ -1973,42 +1806,53 @@ bool ModelManager::assign_compute_backend(const std::vector<ggml_tensor*>& tenso
continue;
}
- const bool params_follow_compute = state->params_follow_compute_backend ||
- state->residency_mode == ResidencyMode::Disk;
- const bool compute_changes = state->compute_backend != compute_backend;
- const bool params_changes = params_follow_compute && state->params_backend != compute_backend;
- if (!compute_changes && !params_changes) {
+ if (state->compute_backend == compute_backend) {
+ if (state->params_follow_compute_backend || state->residency_mode == ResidencyMode::Disk)
+ state->preferred_backend = compute_backend;
continue;
}
-
- if (params_changes)
- detach_shared_weight(*state);
- if (retain_weights_ && state->pin_count == 0 &&
- (state->staged_to_compute_backend || (params_changes && state->loaded_to_params_backend))) {
+ const auto old_device = state->compute_backend ? ggml_backend_get_device(state->compute_backend) : nullptr;
+ const bool same_device = old_device == ggml_backend_get_device(compute_backend);
+ auto on_old_device = [&] {
+ return !same_device && state->params_backend() && !sd_backend_is_cpu(state->params_backend()) &&
+ ggml_backend_get_device(state->params_backend()) == old_device;
+ };
+ auto evict_copy = [&](ggml_backend_buffer_t buffer) {
const auto candidates = evictable_compute_backend_blocks(state->compute_backend, {});
- const auto found = std::find_if(candidates.begin(), candidates.end(), [&](const auto& block) {
- return std::find(block.tensors.begin(), block.tensors.end(), state->tensor) != block.tensors.end();
- });
+ const auto found = std::find_if(candidates.begin(), candidates.end(),
+ [buffer](const auto& block) { return block.buffer == buffer; });
if (found != candidates.end())
evict_compute_backend_block(*found);
- }
- if (params_changes)
- detach_shared_weight(*state);
- if (state->pin_count > 0 || state->staged_to_compute_backend) {
+ };
+ if (state->pin_count() == 0 && state->staged())
+ evict_copy(state->compute_copy()->buffer);
+ if (state->pin_count() > 0 || state->staged()) {
LOG_ERROR("model manager cannot move active tensor '%s' to another compute backend",
state->name.c_str());
return false;
}
- if (params_changes && state->loaded_to_params_backend) {
+ // Params stored on the previous compute device do not follow it to another device.
+ if (state->loaded() && on_old_device()) {
+ if (!resource_of(*state).shared_weights_key_.empty())
+ store_.detach_shared_weight(*state);
+ if (state->loaded())
+ evict_copy(state->storage_copy()->buffer);
+ }
+ // Eviction can move loaded weights to RAM; only weights left on the old device block the move.
+ if (state->loaded() && on_old_device()) {
LOG_ERROR("model manager cannot move loaded tensor '%s' to another params backend",
state->name.c_str());
return false;
}
+ const bool follows = state->params_follow_compute_backend || state->residency_mode == ResidencyMode::Disk;
+ const bool home = state->params_backend() == state->compute_backend;
+ store_.drop_merged_cache(*state);
state->compute_backend = compute_backend;
- if (params_follow_compute) {
- state->params_backend = compute_backend;
- }
+ if (follows)
+ state->preferred_backend = compute_backend;
+ if (!state->loaded() || (same_device && home))
+ store_.reset_location(*state);
}
return true;
@@ -2025,11 +1869,7 @@ size_t ModelManager::compute_backend_alloc_size(const std::vector<TensorState*>&
if (state->usage_op == GGML_OP_CUSTOM && !sd_backend_is_cpu(state->compute_backend) && !needs_lora_staging(*state)) {
continue;
}
- const bool compute_resident =
- state->compute_backend == state->params_backend && !needs_lora_staging(*state)
- ? state->loaded_to_params_backend
- : state->staged_to_compute_backend;
- if (missing_only && compute_resident) {
+ if (missing_only && compute_params_resident(*state)) {
continue;
}
if (!seen.insert(state).second || should_ignore(*state) || (state->sources.empty() && is_optional_missing_tensor(state->name))) {
@@ -2037,7 +1877,8 @@ size_t ModelManager::compute_backend_alloc_size(const std::vector<TensorState*>&
}
ggml_backend_buffer_type_t buffer_type = nullptr;
- if (state->compute_backend == state->params_backend && !needs_lora_staging(*state)) {
+ if (state->compute_backend == state->params_backend() && !needs_lora_staging(*state) &&
+ state->param_source() == ParamSource::Backend && !state->staged()) {
buffer_type = params_buffer_type_for(*state);
} else {
buffer_type = split_buffer_type_for(*state);
@@ -2095,7 +1936,7 @@ size_t ModelManager::compute_backend_resident_bytes(ggml_backend_t compute_backe
for (auto buffer : entry.second.model_loader_.get_device_mmap_buffers())
add_buffer(buffer);
}
- for (const auto& block : params_storage_blocks_) {
+ for (const auto& block : store_.storage_blocks()) {
if (block != nullptr) {
add_buffer(block->buffer);
for (const auto& store : block->mmap_tensor_stores) {
@@ -2103,7 +1944,7 @@ size_t ModelManager::compute_backend_resident_bytes(ggml_backend_t compute_backe
}
}
}
- for (const auto& block : compute_staging_blocks_) {
+ for (const auto& block : store_.compute_blocks()) {
if (block != nullptr) {
add_buffer(block->buffer);
}
@@ -2121,31 +1962,14 @@ size_t ModelManager::compute_backend_resident_bytes(ggml_backend_t compute_backe
}
ModelManager::RAMBudget ModelManager::available_ram_for_fit() const {
- size_t reclaimable = 0;
- auto add = [&](ggml_backend_buffer_t buffer) {
- if (buffer && ggml_backend_buffer_is_host(buffer))
- reclaimable += std::min(ggml_backend_buffer_get_size(buffer), SIZE_MAX - reclaimable);
- };
- std::map<const TensorState*, bool> staged_idle;
- for (const auto& block : compute_staging_blocks_) {
- const bool idle = std::all_of(block->staged_tensors.begin(), block->staged_tensors.end(), [](const auto& entry) {
- return entry.first->pin_count == 0;
- });
- for (const auto& [state, _] : block->staged_tensors)
- staged_idle[state] = idle;
- if (idle)
- add(block->buffer);
- }
- for (const auto& block : params_storage_blocks_)
- if (block->mmap_tensor_stores.empty() && std::all_of(block->states.begin(), block->states.end(), [&](const auto* state) {
- return state->pin_count == 0 && !state->sources.empty() && state->applied_lora_epoch == UINT64_MAX &&
- !state->tensor->view_src && (!state->staged_to_compute_backend || (staged_idle.count(state) && staged_idle.at(state)));
- }))
- add(block->buffer);
- const auto resident = host_weight_bytes();
- const auto fixed = resident - std::min(resident, reclaimable);
- int64_t free = sd::backend_fit::available_ram_bytes();
- const auto commit = sd::backend_fit::available_commit_bytes();
+ // RAM the planner could reclaim for weights, by the same rules as a real reclaim.
+ sd::weights::Request request;
+ request.tier = sd::weights::Tier::Host;
+ const size_t reclaimable = sd::weights::reclaimable_bytes(residency_snapshot(request, nullptr), request);
+ const auto resident = host_weight_bytes();
+ const auto fixed = resident - std::min(resident, reclaimable);
+ int64_t free = sd::backend_fit::available_ram_bytes();
+ const auto commit = sd::backend_fit::available_commit_bytes();
if (commit >= 0)
free = free < 0 ? commit : std::min(free, commit);
constexpr size_t reserve = 1024ULL * 1024 * 1024;
@@ -2158,13 +1982,11 @@ ModelManager::RAMBudget ModelManager::available_ram_for_fit() const {
size_t ModelManager::available_vram_for_fit(ggml_backend_t backend, size_t free_bytes, size_t total_bytes) const {
if (backend == nullptr || total_bytes == 0 || free_bytes > total_bytes)
return free_bytes;
- size_t reclaimable = 0;
- for (const auto& block : evictable_compute_backend_blocks(backend, {}))
- reclaimable += std::min(block.bytes, total_bytes - reclaimable);
- const auto resident = compute_backend_resident_bytes(backend);
- const auto limit = max_vram_.bytes_for_backend(backend);
- const auto remaining = resident - std::min(resident, reclaimable) + other_runtime_resident_bytes(0, backend);
- size_t available = free_bytes + std::min(reclaimable, total_bytes - free_bytes);
+ const size_t reclaimable = std::min(reclaimable_bytes({backend}, backend, {}, {}), total_bytes);
+ const auto resident = compute_backend_resident_bytes(backend);
+ const auto limit = max_vram_.bytes_for_backend(backend);
+ const auto remaining = resident - std::min(resident, reclaimable) + other_runtime_resident_bytes(0, backend);
+ size_t available = free_bytes + std::min(reclaimable, total_bytes - free_bytes);
if (limit > 0)
available = std::min(available, limit > remaining ? limit - remaining : 0);
return available;
@@ -2205,52 +2027,6 @@ size_t ModelManager::other_runtime_resident_bytes(uintptr_t owner_id,
return total_size;
}
-bool ModelManager::prepare_params(const std::vector<ggml_tensor*>& tensors) {
- if (tensors.empty()) {
- return true;
- }
-
- std::vector<TensorState*> required_states;
- if (!resolve_required_tensor_states(tensors, required_states)) {
- return false;
- }
-
- for (const auto* state : required_states) {
- if (state != nullptr && state->sources.empty()) {
- LOG_ERROR("required tensor '%s' is missing from model metadata", state->name.c_str());
- return false;
- }
- }
-
- if (!load_tensors_to_params_backend(required_states)) {
- return false;
- }
-
- if (!stage_tensors_to_compute_backend(required_states) ||
- (retain_weights_ && !ensure_host_capacity(0, required_states))) {
- const std::unordered_set<TensorState*> failed(required_states.begin(), required_states.end());
- release_compute_staging_blocks(false, &failed);
- release_params_storage_blocks(false, &failed);
- return false;
- }
-
- // LoRA execution may reclaim other residency blocks while these weights are in use.
- const uint64_t use_epoch = ++residency_epoch_;
- for (TensorState* state : required_states) {
- if (state != nullptr) {
- state->pin_count++;
- state->last_use_epoch = use_epoch;
- }
- }
- if (!apply_loras_to_params(required_states)) {
- finish_compute_backend_usage(required_states);
- std::unordered_set<TensorState*> failed(required_states.begin(), required_states.end());
- invalidate_sources(failed);
- return false;
- }
- return true;
-}
-
void ModelManager::finish_compute_backend_usage(const std::vector<TensorState*>& states) {
if (states.empty()) {
return;
@@ -2261,9 +2037,7 @@ void ModelManager::finish_compute_backend_usage(const std::vector<TensorState*>&
if (state == nullptr || !target_states.insert(state).second) {
continue;
}
- if (state->pin_count > 0) {
- state->pin_count--;
- }
+ store_.release_lease(*state);
}
}
@@ -2278,67 +2052,6 @@ void ModelManager::release_compute_backend_params(const std::vector<ggml_tensor*
finish_compute_backend_usage(required_states);
}
-void ModelManager::evict_compute_backend_params(const std::vector<ggml_tensor*>& tensors) {
- if (tensors.empty()) {
- return;
- }
- std::unordered_set<TensorState*> target_states;
- // Session cleanup may follow unregistration, after tensor metadata has been freed.
- for (auto* tensor : tensors) {
- const auto found = tensor_states_by_tensor_.find(tensor);
- if (found != tensor_states_by_tensor_.end() &&
- (!retain_weights_ || found->second->residency_mode == ResidencyMode::Disk)) {
- target_states.insert(found->second);
- }
- }
- if (target_states.empty()) {
- return;
- }
-
- for (const auto& block : compute_staging_blocks_) {
- const bool intersects = std::any_of(
- block->staged_tensors.begin(),
- block->staged_tensors.end(),
- [&](const std::pair<TensorState*, ggml_tensor*>& pair) {
- return pair.first != nullptr && target_states.count(pair.first) > 0;
- });
- const bool fully_evictable = std::all_of(
- block->staged_tensors.begin(),
- block->staged_tensors.end(),
- [](const std::pair<TensorState*, ggml_tensor*>& pair) {
- return pair.first == nullptr || pair.first->pin_count == 0;
- });
- if (intersects && fully_evictable) {
- for (const auto& pair : block->staged_tensors) {
- if (pair.first != nullptr) {
- target_states.insert(pair.first);
- }
- }
- }
- }
- release_compute_staging_blocks(false, &target_states);
-
- for (const auto& block : params_storage_blocks_) {
- const bool intersects = std::any_of(
- block->states.begin(),
- block->states.end(),
- [&](TensorState* state) {
- return state != nullptr && target_states.count(state) > 0;
- });
- const bool fully_evictable = std::all_of(
- block->states.begin(),
- block->states.end(),
- [](TensorState* state) {
- return state == nullptr ||
- (state->pin_count == 0 && !state->staged_to_compute_backend &&
- state->residency_mode == ResidencyMode::Disk);
- });
- if (intersects && fully_evictable) {
- target_states.insert(block->states.begin(), block->states.end());
- }
- }
- release_params_storage_blocks(false, &target_states);
-}
WeightResidencyInfo ModelManager::inspect_compute_backend_params(
const std::vector<ggml_tensor*>& tensors) const {
WeightResidencyInfo info;
@@ -2356,21 +2069,19 @@ WeightResidencyInfo ModelManager::inspect_compute_backend_params(
(state->sources.empty() && is_optional_missing_tensor(state->name))) {
continue;
}
- const bool compute_resident =
- state->compute_backend == state->params_backend && !needs_lora_staging(*state)
- ? state->loaded_to_params_backend
- : state->staged_to_compute_backend;
- if (compute_resident) {
+ if (compute_params_resident(*state)) {
continue;
}
has_missing_params = true;
- if (state->usage_op == GGML_OP_CUSTOM || has_lora_int8_pair(*state)) {
+ // A merged weight uploads from its RAM cache; an INT8 pair without one stages synchronously.
+ const bool cached = reusable_lora_weight(*state) != nullptr;
+ if (state->usage_op == GGML_OP_CUSTOM || (has_lora_int8_pair(*state) && !cached)) {
single_prefetch_buffer = false;
}
if (split_buffer_type_for(*state) != nullptr) {
prefetch_candidate = false;
}
- if (state->compute_backend == state->params_backend ||
+ if ((!cached && (state->compute_backend == state->params_backend() || state->param_source() != ParamSource::Backend)) ||
state->compute_backend == nullptr || sd_backend_is_cpu(state->compute_backend)) {
prefetch_candidate = false;
continue;
@@ -2418,7 +2129,7 @@ void ModelManager::remove_runtime_owner(uintptr_t owner_id) {
std::map<ggml_backend_t, size_t> ModelManager::split_devices_for(const std::vector<TensorState*>& states) const {
std::map<ggml_backend_t, size_t> devices;
for (const auto* state : states) {
- const auto& placements = state->resource->split_buffer_limits_;
+ const auto& placements = resource_of(*state).split_buffer_limits_;
auto placement = placements.find(split_buffer_type_for(*state));
if (placement == placements.end())
continue;
@@ -2435,122 +2146,48 @@ ModelManager::CapacityCheck ModelManager::check_capacity(
const DeviceMemoryRequest& request,
const std::vector<TensorState*>& states,
DeviceMemoryCheck check,
- bool log_details) const {
- CapacityCheck result;
- if (request.compute_backend == nullptr || sd_backend_is_cpu(request.compute_backend)) {
- return result;
- }
- auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; };
- const size_t missing = compute_backend_alloc_size(states, true);
- // Backend scratch buffers and pipelines are not included in graph measurements.
- size_t safety_margin = 512ULL * 1024ULL * 1024ULL;
+ bool log_details,
+ const ReclaimScope& scope) const {
+ if (request.compute_backend == nullptr || sd_backend_is_cpu(request.compute_backend))
+ return {};
+ auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; };
+ sd::weights::CapacityDemand demand;
+ demand.missing_weights = compute_backend_alloc_size(states, true);
+ demand.pending_runtime = request.pending_allocation_bytes;
+ demand.resident_runtime = request.runtime_resident_bytes;
+ demand.reused_allocation = add(request.reused_buffer_bytes,
+ request.prefetch_buffer && request.prefetch_buffer->buffer ? request.prefetch_buffer->bytes : 0);
+ demand.safety_margin = 512ULL * 1024ULL * 1024ULL;
#ifdef _WIN32
- if (sd_backend_is(request.compute_backend, "CUDA")) {
- // Avoid WDDM allocation churn when transient buffers compete with reusable staging buffers.
- safety_margin = 1024ULL * 1024ULL * 1024ULL;
- }
+ // Avoid WDDM allocation churn when transient buffers compete with reusable staging buffers.
+ if (sd_backend_is(request.compute_backend, "CUDA"))
+ demand.safety_margin = 1024ULL * 1024ULL * 1024ULL;
#endif
- const size_t prefetch_reused_bytes = request.prefetch_buffer && request.prefetch_buffer->buffer ? request.prefetch_buffer->bytes : 0;
- const size_t reused_bytes = add(request.reused_buffer_bytes, prefetch_reused_bytes);
- const size_t pending_bytes = add(request.pending_allocation_bytes, missing);
- const size_t allocation_bytes = pending_bytes - std::min(pending_bytes, reused_bytes);
- // WDDM can report zero free memory even after all buffers for the graph have been allocated.
- result.required_device_bytes = allocation_bytes == 0 ? 0 : add(allocation_bytes, safety_margin);
- result.required_budget_bytes = add(request.runtime_peak_bytes(), missing);
-
- const bool allow_reclamation = check == DeviceMemoryCheck::Reclaimable;
- std::vector<ggml_tensor*> protected_params;
- if (allow_reclamation && retain_weights_) {
- protected_params.reserve(states.size());
- for (const auto* state : states)
- protected_params.push_back(state->tensor);
- }
- auto account_device = [&](ggml_backend_t backend, size_t limit) {
+ demand.reclaim = check == DeviceMemoryCheck::Reclaimable;
+
+ // Snapshot every device the request touches; the evaluation itself reads no live state.
+ std::vector<sd::weights::DeviceSnapshot> snapshots;
+ auto snapshot = [&](ggml_backend_t backend, size_t limit) {
auto device = ggml_backend_get_device(backend);
if (device == nullptr)
return;
- const size_t weights_resident = compute_backend_resident_bytes(backend);
- const size_t other_runtime = other_runtime_resident_bytes(request.owner_id, backend);
- size_t reclaimable = 0;
- if (allow_reclamation && retain_weights_) {
- for (const auto& block : evictable_compute_backend_blocks(backend, protected_params))
- reclaimable += std::min(block.bytes, weights_resident - reclaimable);
- }
- const size_t resident = add(weights_resident - reclaimable, other_runtime);
-
- if (retain_weights_) {
- const auto shared_limit = max_vram_.bytes_for_backend(backend);
- if (shared_limit > 0)
- limit = limit == 0 ? shared_limit : std::min(limit, shared_limit);
- }
-
- size_t free_bytes = 0, total_bytes = 0, cached_bytes = 0;
- const bool has_cache_accounting = sd_backend_get_buffer_cache_memory(device, free_bytes, total_bytes, cached_bytes);
- if (check == DeviceMemoryCheck::TrimBufferCache) {
- if (has_cache_accounting) {
- const size_t in_use = add(resident, request.runtime_resident_bytes);
- const size_t peak = add(resident, result.required_budget_bytes);
- // If trimming alone cannot admit a prefetch, an evicted weight buffer may satisfy it without growing the pool.
- const bool wait_for_eviction = request.prefetch_buffer && !request.prefetch_buffer->buffer &&
- limit > 0 && peak > limit && add(in_use, cached_bytes) <= limit;
- size_t cache_limit = limit == 0 ? SIZE_MAX : limit - std::min(limit, wait_for_eviction ? in_use : peak);
- if (!wait_for_eviction && total_bytes > 0 && free_bytes < result.required_device_bytes) {
- const size_t shortfall = result.required_device_bytes - free_bytes;
- cache_limit = std::min(cache_limit, cached_bytes - std::min(cached_bytes, shortfall));
- }
- sd_backend_set_buffer_cache_limit(device, cache_limit);
- if (cached_bytes > cache_limit) {
- const size_t previous_cached_bytes = cached_bytes;
- sd_backend_get_buffer_cache_memory(device, free_bytes, total_bytes, cached_bytes);
- // Virtual CUDA devices may regain only a fraction of the bytes released.
- if (cached_bytes > 0 && free_bytes < result.required_device_bytes) {
- sd_backend_set_buffer_cache_limit(device, 0);
- sd_backend_get_buffer_cache_memory(device, free_bytes, total_bytes, cached_bytes);
- }
- LOG_DEBUG("model manager trimmed the idle buffer pool on %s from %.2f MiB to %.2f MiB",
- ggml_backend_name(backend), previous_cached_bytes / (1024.0 * 1024.0), cached_bytes / (1024.0 * 1024.0));
- }
- } else if (limit > 0) {
- // An older backend may expose reuse without exposing the retained bytes.
- sd_backend_set_buffer_cache_enabled(backend, false);
- ggml_backend_dev_memory(device, &free_bytes, &total_bytes);
- }
- } else if (allow_reclamation && cached_bytes > 0) {
- ggml_backend_dev_memory(device, &free_bytes, &total_bytes);
- cached_bytes = 0;
- }
-
- const size_t committed = add(resident, cached_bytes);
- if (limit > 0) {
- result.requires_reclamation |= committed > limit;
- result.available_budget_bytes = std::min(result.available_budget_bytes, limit - std::min(limit, committed));
- }
- if (log_details) {
- LOG_WARN("model manager memory on %s: reported free %.2f MiB / total %.2f MiB, tracked weights %.2f MiB / other runtime %.2f MiB / current runtime %.2f MiB / idle buffer pool %.2f MiB",
- ggml_backend_name(backend),
- free_bytes / (1024.0 * 1024.0), total_bytes / (1024.0 * 1024.0),
- weights_resident / (1024.0 * 1024.0), other_runtime / (1024.0 * 1024.0),
- request.runtime_resident_bytes / (1024.0 * 1024.0), cached_bytes / (1024.0 * 1024.0));
- }
- if (free_bytes == 0 && total_bytes == 0)
- return;
- // Vulkan's heap budget subtraction can underflow when usage exceeds the budget.
- if (total_bytes > 0 && free_bytes > total_bytes && sd_backend_is(backend, "Vulkan")) {
- if (ggml_backend_dev_type(device) != GGML_BACKEND_DEVICE_TYPE_IGPU) {
- result.available_device_bytes = 0;
- return;
- }
- LOG_VERBOSE("ignoring impossible free memory report on %s (%.2f MB free / %.2f MB total), using tracked residency",
- ggml_backend_name(backend), free_bytes / (1024.0 * 1024.0), total_bytes / (1024.0 * 1024.0));
- free_bytes = total_bytes;
- result.wrapped_device_report = true;
- }
- free_bytes = add(free_bytes, reclaimable);
- if (total_bytes > 0) {
- const size_t used = add(committed, add(request.runtime_resident_bytes, reused_bytes));
- free_bytes = std::min(free_bytes, used < total_bytes ? total_bytes - used : 0);
- }
- result.available_device_bytes = std::min(result.available_device_bytes, free_bytes);
+ sd::weights::DeviceSnapshot item;
+ item.backend = backend;
+ item.device = device;
+ item.weights_resident = compute_backend_resident_bytes(backend);
+ item.other_runtime = other_runtime_resident_bytes(request.owner_id, backend);
+ if (demand.reclaim) {
+ // The same actions plan_reclaim() executes; weights that load again count against them.
+ item.reclaimable = reclaimable_bytes(request, backend, states, states, scope);
+ }
+ const auto shared_limit = max_vram_.bytes_for_backend(backend);
+ item.limit = shared_limit > 0 ? (limit == 0 ? shared_limit : std::min(limit, shared_limit)) : limit;
+ item.pool_accounted = sd_backend_get_buffer_cache_memory(device, item.free_bytes, item.total_bytes, item.pool_bytes);
+ if (demand.reclaim && item.pool_bytes > 0)
+ ggml_backend_dev_memory(device, &item.free_without_pool, &item.total_without_pool);
+ item.vulkan = sd_backend_is(backend, "Vulkan");
+ item.integrated = ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_IGPU;
+ snapshots.push_back(item);
};
// GGML exposes only the split buffer's total size, so charge it on each participant.
auto devices = split_devices_for(states);
@@ -2561,9 +2198,22 @@ ModelManager::CapacityCheck ModelManager::check_capacity(
primary_limit = primary_limit == 0 ? primary->second : std::min(primary_limit, primary->second);
devices.erase(primary);
}
- account_device(request.compute_backend, primary_limit);
+ snapshot(request.compute_backend, primary_limit);
for (const auto& [backend, limit] : devices)
- account_device(backend, limit);
+ snapshot(backend, limit);
+
+ auto result = sd::weights::evaluate_capacity(demand, snapshots);
+ for (const auto& item : snapshots) {
+ if (log_details) {
+ LOG_WARN("model manager memory on %s: reported free %.2f MiB / total %.2f MiB, tracked weights %.2f MiB / other runtime %.2f MiB / current runtime %.2f MiB / idle buffer pool %.2f MiB",
+ ggml_backend_name(item.backend), item.free_bytes / (1024.0 * 1024.0), item.total_bytes / (1024.0 * 1024.0),
+ item.weights_resident / (1024.0 * 1024.0), item.other_runtime / (1024.0 * 1024.0),
+ request.runtime_resident_bytes / (1024.0 * 1024.0), item.pool_bytes / (1024.0 * 1024.0));
+ }
+ if (item.vulkan && item.integrated && item.total_bytes > 0 && item.free_bytes > item.total_bytes)
+ LOG_VERBOSE("ignoring impossible free memory report on %s (%.2f MB free / %.2f MB total), using tracked residency",
+ ggml_backend_name(item.backend), item.free_bytes / (1024.0 * 1024.0), item.total_bytes / (1024.0 * 1024.0));
+ }
return result;
}
@@ -2581,138 +2231,6 @@ DeviceMemoryCapacity ModelManager::inspect_compute_backend_capacity(
return check_capacity(request, states, check, log_details);
}
-std::vector<WeightResidencyBlock> ModelManager::evictable_compute_backend_blocks(
- ggml_backend_t backend,
- const std::vector<ggml_tensor*>& protected_params) const {
- std::vector<WeightResidencyBlock> result;
- if (backend == nullptr) {
- return result;
- }
- std::vector<TensorState*> protected_list;
- if (!resolve_required_tensor_states(protected_params, protected_list)) {
- return result;
- }
- std::unordered_set<TensorState*> protected_states(protected_list.begin(), protected_list.end());
- protect_prefetched_states(protected_states);
- const auto device = ggml_backend_get_device(backend);
- const bool cpu = sd_backend_is_cpu(backend);
- auto on_device = [&](ggml_backend_buffer_t buffer) {
- if (buffer == nullptr) {
- return false;
- }
- if (cpu) {
- return ggml_backend_buffer_is_host(buffer);
- }
- if (ggml_backend_buffer_is_host(buffer)) {
- return false;
- }
- const auto type = ggml_backend_buffer_get_type(buffer);
- const auto split = split_buffer_devices_.find(type);
- if (split != split_buffer_devices_.end()) {
- return std::any_of(split->second.begin(), split->second.end(), [&](const auto& entry) {
- return ggml_backend_get_device(entry.first) == device;
- });
- }
- return ggml_backend_buft_get_device(type) == device;
- };
- auto append = [&](ggml_backend_buffer_t buffer, const std::vector<TensorState*>& states, bool storage) {
- if (!on_device(buffer) || states.empty()) {
- return;
- }
- WeightResidencyBlock candidate;
- candidate.buffer = buffer;
- candidate.backend = backend;
- candidate.bytes = ggml_backend_buffer_get_size(buffer);
- candidate.next_use = planned_next_use_.empty() ? 0 : SIZE_MAX;
- for (auto* state : states) {
- if (state == nullptr) {
- continue;
- }
- if (state->pin_count != 0 || protected_states.count(state) != 0) {
- return;
- }
- if (storage) {
- if (state->staged_to_compute_backend) {
- return;
- }
- if (state->residency_mode != ResidencyMode::Disk) {
- const bool direct_gpu_storage = !cpu && state->params_backend &&
- !sd_backend_is_cpu(state->params_backend) &&
- state->compute_backend == state->params_backend;
- if ((!retain_weights_ && !direct_gpu_storage) ||
- state->sources.empty() || state->applied_lora_epoch != UINT64_MAX ||
- state->split_buffer_type != nullptr || state->tensor->view_src != nullptr) {
- return;
- }
- candidate.requires_demotion = true;
- }
- }
- candidate.tensors.push_back(state->tensor);
- candidate.next_use = std::min(candidate.next_use, next_weight_use(*state));
- candidate.last_use_epoch = std::max(candidate.last_use_epoch, state->last_use_epoch);
- }
- result.push_back(std::move(candidate));
- };
- for (const auto& block : compute_staging_blocks_) {
- std::vector<TensorState*> states;
- states.reserve(block->staged_tensors.size());
- for (const auto& entry : block->staged_tensors) {
- states.push_back(entry.first);
- }
- append(block->buffer, states, false);
- }
- for (const auto& block : params_storage_blocks_) {
- // Loader-retained mappings cannot be reclaimed by freeing a storage block.
- if (block->mmap_tensor_stores.empty()) {
- append(block->buffer, block->states, true);
- }
- }
- return result;
-}
-
-bool ModelManager::evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer) {
- const auto candidates = evictable_compute_backend_blocks(block.backend, {});
- const auto found = std::find_if(candidates.begin(), candidates.end(), [&](const auto& candidate) {
- return candidate.buffer == block.buffer && candidate.tensors == block.tensors &&
- candidate.requires_demotion == block.requires_demotion;
- });
- if (found == candidates.end()) {
- return false;
- }
- for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end(); ++it) {
- if ((*it)->buffer == block.buffer) {
- LOG_DEBUG("model manager evicted %.2f MiB of staged weights on %s",
- block.bytes / (1024.0 * 1024.0), ggml_backend_name(block.backend));
- if (prefetch_buffer != nullptr && !prefetch_buffer->buffer &&
- prefetch_buffer->bytes == block.bytes && prefetch_buffer->type == ggml_backend_buffer_get_type(block.buffer)) {
- // The old weights are unpinned. Hand the allocation to the next upload before it can enter the idle pool.
- prefetch_buffer->buffer.reset((*it)->buffer);
- (*it)->buffer = nullptr;
- }
- free_compute_staging_block(**it);
- compute_staging_blocks_.erase(it);
- return true;
- }
- }
- for (auto it = params_storage_blocks_.begin(); it != params_storage_blocks_.end(); ++it) {
- if ((*it)->buffer == block.buffer) {
- LOG_DEBUG("model manager evicted %.2f MiB of weight storage on %s",
- block.bytes / (1024.0 * 1024.0), ggml_backend_name(block.backend));
- if (block.requires_demotion && !retain_weights_) {
- for (auto* state : (*it)->states) {
- if (state != nullptr) {
- state->residency_mode = ResidencyMode::Disk;
- }
- }
- }
- free_params_storage_block(**it);
- params_storage_blocks_.erase(it);
- return true;
- }
- }
- return false;
-}
-
bool ModelManager::fits_compute_backend_capacity(
const DeviceMemoryRequest& request,
const std::vector<ggml_tensor*>& required_params,
@@ -2732,10 +2250,12 @@ bool ModelManager::ensure_compute_backend_capacity(
const std::vector<std::vector<ggml_tensor*>>& preferred_eviction_order,
const std::vector<ggml_tensor*>& protected_params,
std::string* device_memory_error) {
- if (retain_weights_) {
+ {
std::vector<TensorState*> states;
if (!resolve_required_tensor_states(required_params, states, request.compute_backend))
return false;
+ if (request.compute_backend && !sd_backend_is_cpu(request.compute_backend))
+ place_first_loads(request, states);
const auto devices = split_devices_for(states);
if (devices.size() > 1) {
auto protected_weights = protected_params;
@@ -2748,10 +2268,10 @@ bool ModelManager::ensure_compute_backend_capacity(
const DeviceMemoryRequest peer{backend, request.owner_id,
pending > SIZE_MAX - missing ? SIZE_MAX : pending + missing,
request.runtime_resident_bytes, limit};
- if (!execution_engine()->ensure_capacity(*this, peer, {}, preferred_eviction_order, protected_weights, device_memory_error))
+ if (!ensure_device_capacity(peer, {}, preferred_eviction_order, protected_weights, device_memory_error))
return false;
}
}
}
- return execution_engine()->ensure_capacity(*this, request, required_params, preferred_eviction_order, protected_params, device_memory_error);
+ return ensure_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 6fe8cd1..6f4ca99 100644
--- a/src/model_manager.h
+++ b/src/model_manager.h
@@ -8,6 +8,7 @@
#include <memory>
#include <set>
#include <string>
+#include <tuple>
#include <unordered_set>
#include <vector>
@@ -15,15 +16,28 @@
#include "device_residency_manager.h"
#include "model_component.h"
#include "model_loader.h"
+#include "weights/reclaim_planner.h"
+#include "weights/store.h"
+#include "weights/weight_reader.h"
+#include "weights/weight_transfer.h"
struct LoraModel;
+namespace sd::lora {
+ struct MergeCandidate;
+ struct MergeContext;
+}
+
+// Limits which resident weights a reclaim may copy away. Declared outside ModelManager: clang
+// rejects `= {}` default arguments of a nested type with default member initializers.
+struct ReclaimScope {
+ // A first load keeps resident weights of these resources and those needed sooner.
+ const std::unordered_set<sd::weights::ResourceId>* keep_resources = nullptr;
+ size_t keep_next_use = 0;
+};
class ModelManager : public DeviceResidencyManager {
public:
- enum class ResidencyMode {
- Disk,
- ParamBackend,
- };
+ using ResidencyMode = sd::weights::ResidencyMode;
using ResourceId = uint64_t;
@@ -75,6 +89,8 @@ private:
bool segmented_compute_disabled_ = false;
bool prefetch_disabled_ = false;
bool layer_split_ = false;
+ // Devices a layer split spans; tensors move to them only when the first graph is built.
+ std::vector<ggml_backend_t> layer_split_backends_;
};
Resource default_resource_;
@@ -82,60 +98,32 @@ private:
std::map<ResourceId, Resource> resources_;
ResourceId next_resource_id_ = 1;
std::map<std::string, size_t> planned_next_use_;
- bool retain_weights_ = false;
mutable sd::ggml_graph_cut::MaxVramAssignment max_vram_;
size_t max_ram_bytes_ = 0;
std::string host_memory_error_;
std::function<bool()> evict_idle_resource_;
- struct TensorState {
- Resource* resource = nullptr;
- std::string name;
- ggml_tensor* tensor = nullptr;
- ModelComponent component = ModelComponent::Count;
- std::vector<TensorStorage> sources;
- ModelLoader::FileId source_file = 0;
- SDVersion source_version = VERSION_COUNT;
-
- ResidencyMode residency_mode = ResidencyMode::ParamBackend;
- ggml_backend_t compute_backend = nullptr;
- ggml_backend_t params_backend = nullptr;
- ggml_backend_buffer_type_t split_buffer_type = nullptr;
- bool params_follow_compute_backend = false;
- bool metadata_validated = false;
- enum ggml_op usage_op = GGML_OP_NONE;
- TensorState* lora_int8_partner = nullptr;
- bool is_int8_weight = false;
-
- int pin_count = 0;
-
- bool loaded_to_params_backend = false;
- bool staged_to_compute_backend = false;
- uint64_t applied_lora_epoch = UINT64_MAX;
- uint64_t last_use_epoch = 0;
- };
-
- struct ParamsStorageBlock {
- ggml_backend_buffer_t buffer = nullptr;
- std::vector<MmapTensorStore> mmap_tensor_stores;
- std::vector<TensorState*> states;
- bool shared = false;
- };
+ using ParamSource = sd::weights::ParamSource;
+ using CachedLoraWeight = sd::weights::CachedLoraWeight;
+ using TensorState = sd::weights::TensorState;
+ using ParamsStorageBlock = sd::weights::ParamsStorageBlock;
+ using ComputeStagingBlock = sd::weights::ComputeStagingBlock;
+ using WeightStore = sd::weights::WeightStore;
- struct ComputeStagingBlock {
- ggml_backend_t compute_backend = nullptr;
- ggml_backend_buffer_t buffer = nullptr;
- ggml_context* staging_ctx = nullptr;
- std::vector<std::pair<TensorState*, ggml_tensor*>> staged_tensors;
- };
+ // Weight states keep their resource as an opaque identifier.
+ static Resource& resource_of(const TensorState& state) { return *static_cast<Resource*>(state.resource); }
+ static Resource* resource_ptr(const TensorState& state) { return static_cast<Resource*>(state.resource); }
struct PrefetchBlock {
std::vector<TensorState*> states;
- ggml_backend_t compute_backend = nullptr;
- ggml_backend_t transfer_backend = nullptr;
- ggml_backend_event_t event = nullptr;
- bool submitted = false;
+ ggml_backend_t compute_backend = nullptr;
+ sd::weights::PendingTransfer transfer;
std::vector<std::unique_ptr<ComputeStagingBlock>> staging_blocks;
+ // Merged weights upload from their RAM cache; holding it keeps the source alive.
+ std::map<const TensorState*, std::shared_ptr<const CachedLoraWeight>> merged;
+ // The storage epoch of each original when its upload was queued. A merge in place
+ // afterwards leaves the uploaded bytes stale.
+ std::map<const TensorState*, uint64_t> source_epochs;
};
struct RuntimeResidency {
@@ -149,25 +137,24 @@ private:
};
// Auxiliary models retain their own catalogs and conversion settings.
- std::vector<std::unique_ptr<TensorState>> tensor_states_;
- std::map<const ggml_tensor*, TensorState*> tensor_states_by_tensor_;
+ WeightStore store_{&ModelManager::needs_lora_staging};
mutable std::list<ResolvedTensorStates> resolved_tensor_states_;
- std::vector<std::unique_ptr<ParamsStorageBlock>> params_storage_blocks_;
- std::vector<std::unique_ptr<ComputeStagingBlock>> compute_staging_blocks_;
std::map<ggml_backend_buffer_type_t, std::vector<std::pair<ggml_backend_t, size_t>>> split_buffer_devices_;
std::map<uintptr_t, std::unique_ptr<PrefetchBlock>> prefetch_blocks_;
- std::map<ggml_backend_t, ggml_backend_t> prefetch_backends_;
+ // A batched merge needs its completed copies until the full request is ready again.
+ const std::unordered_set<TensorState*>* lora_batch_spills_ = nullptr;
+ sd::weights::WeightTransfer transfer_;
std::map<std::pair<uintptr_t, ggml_backend_t>, RuntimeResidency> runtime_residencies_;
std::unordered_set<uintptr_t> runtime_owners_;
uint64_t residency_epoch_ = 0;
+ mutable std::unique_ptr<ggml_backend, decltype(&ggml_backend_free)> host_backend_{nullptr, ggml_backend_free};
void finish_compute_backend_usage(const std::vector<TensorState*>& states);
void release_all();
void invalidate_sources(const std::unordered_set<TensorState*>& states);
- ggml_backend_t prefetch_backend_for(ggml_backend_t compute_backend);
+ static const ggml_tensor* prefetch_source(const PrefetchBlock& block, const TensorState& state);
bool populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer* prefetch_buffer);
- void synchronize_prefetch_block(PrefetchBlock& block);
void free_prefetch_block(PrefetchBlock& block);
void protect_prefetched_states(std::unordered_set<TensorState*>& states) const;
void clear_all_prefetched_params();
@@ -181,25 +168,98 @@ private:
bool is_optional_missing_tensor(const std::string& name) const;
bool validate_tensor(const TensorState& state) const;
- bool load_tensors_to_params_backend(const std::vector<TensorState*>& states);
+ // capacity_failure reports that device memory ran out; the caller then retries with less.
+ bool load_tensors_to_params_backend(const std::vector<TensorState*>& states, bool* capacity_failure = nullptr);
void reuse_shared_weights(std::vector<TensorState*>& need_load);
- void detach_shared_weight(TensorState& state);
static bool has_lora_int8_pair(const TensorState& state);
static bool needs_lora_staging(const TensorState& state);
- bool apply_loras_to_params(const std::vector<TensorState*>& states);
+ static bool compute_params_resident(const TensorState& state);
+ static const CachedLoraWeight* reusable_lora_weight(const TensorState& state);
+ bool cache_merged_lora_weights(const ComputeStagingBlock& block);
+ bool preserves_batch_merge(TensorState& state) const;
+ size_t cached_lora_bytes() const;
+ // Disk residency keeps no copy above the model file, so its weights load on the compute device.
+ static ggml_backend_t home_backend(const TensorState& state) { return sd::weights::home_backend(state); }
+ void place_first_loads(const DeviceMemoryRequest& request, const std::vector<TensorState*>& states);
+ // Reclaim actions on one device. Required weights may be reclaimed when they must load again
+ // afterwards; other protected weights stay, except LoRA originals that only feed merges.
+ static sd::weights::Request make_reclaim_request(ggml_backend_t backend,
+ bool allow_moves,
+ const std::vector<TensorState*>& required = {},
+ const std::vector<TensorState*>& protected_states = {},
+ const ReclaimScope& scope = {});
+ std::vector<WeightResidencyBlock> reclaim_candidates(ggml_backend_t backend, const sd::weights::Request& plan) const;
+ // Net bytes the same actions free, for capacity checks that do not execute them.
+ size_t reclaimable_bytes(const DeviceMemoryRequest& request,
+ ggml_backend_t backend,
+ const std::vector<TensorState*>& required,
+ const std::vector<TensorState*>& protected_states,
+ const ReclaimScope& scope = {}) const;
+ static WeightResidencyBlock reclaim_block(const sd::weights::Action& action, ggml_backend_t backend);
+ ggml_backend_t host_backend_for(const TensorState& state) const;
+ // The storage copy of a loaded weight; views and untracked data share view_storage_.
+ // The block holds copies below their params location, e.g. after leaving the device.
+ static bool below_home(const ParamsStorageBlock& block) { return sd::weights::below_home(block); }
+ ggml_backend_t next_residency_backend(const TensorState& state, ggml_backend_t from) const;
+ 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,
+ 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);
+ // 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);
+ 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);
+ // A merge target and its optional INT8 scale. A scale requested on its own is the target.
+ struct MergeUnit {
+ TensorState* target;
+ TensorState* scale = nullptr;
+ };
+ // Whether a resource's LoRA version merges into this weight; the one place that selects targets.
+ bool lora_merge_target(const TensorState& state) const;
+ bool merge_pending(const TensorState& state) const;
+ std::vector<MergeUnit> pending_merges(const std::vector<TensorState*>& states) const;
+ // The units as copies for the LoRA layer to write; fails when a copy is not ready.
+ bool merge_candidates(Resource& resource,
+ const std::vector<MergeUnit>& units,
+ std::vector<sd::lora::MergeCandidate>& candidates,
+ std::vector<TensorState*>& owners);
+ sd::lora::MergeContext merge_context(Resource& resource, const std::set<std::string>& model_tensor_names);
+ void commit_merged(const std::vector<TensorState*>& states, uint64_t epoch);
+ // Drops copies a failed merge may have partly written.
+ void abandon_merge(const std::vector<TensorState*>& states);
+ // 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);
+ // 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,
std::vector<ParamsStorageBlock*>& created_storage_blocks);
static std::vector<TensorStorage> find_tensor_sources(const TensorState& state, const String2TensorStorage& sources);
- bool load_tensor_parts(TensorState& state);
+ // Where a weight's data comes from in its model file, delivered into destination.
+ static sd::weights::ReadTarget read_target(const TensorState& state, ggml_tensor* destination);
bool can_mmap_storage(const TensorState& state) const;
size_t host_weight_bytes() const;
- bool evict_host_weight_block(const std::unordered_set<TensorState*>& protected_states);
- bool ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation = true, size_t pending_device_commit = 0);
+ // Executes the first RAM reclaim action the planner allows.
+ bool evict_host_weight_block(const std::unordered_set<TensorState*>& protected_states, const sd::weights::PriorityLimit* limit);
+ // reload: weights whose device reload size the plan needs, i.e. the request's weights.
+ sd::weights::Snapshot residency_snapshot(const sd::weights::Request& plan, ggml_backend_t backend) const;
+ bool fits_host_capacity(size_t pending, bool weight_allocation, size_t pending_device_commit, size_t& available) const;
+ bool ensure_host_capacity(size_t pending, const std::vector<TensorState*>& required_states, bool weight_allocation = true, size_t pending_device_commit = 0, bool optional = false, const sd::weights::PriorityLimit* limit = nullptr);
bool alloc_params_buffers(const std::vector<TensorState*>& states,
const std::vector<TensorState*>& required_states,
- std::vector<ParamsStorageBlock*>& created_storage_blocks);
+ std::vector<ParamsStorageBlock*>& created_storage_blocks,
+ bool* capacity_failure = nullptr);
bool load_tensors(const std::vector<TensorState*>& states);
- bool stage_tensors_to_compute_backend(const std::vector<TensorState*>& states);
+ bool stage_tensors_to_compute_backend(const std::vector<TensorState*>& states, bool& capacity_failure);
size_t compute_backend_alloc_size(const std::vector<TensorState*>& states,
bool missing_only) const;
size_t compute_backend_resident_bytes(ggml_backend_t compute_backend) const;
@@ -208,18 +268,12 @@ private:
CapacityCheck check_capacity(const DeviceMemoryRequest& request,
const std::vector<TensorState*>& states,
DeviceMemoryCheck check,
- bool log_details = false) const;
+ bool log_details = false,
+ const ReclaimScope& scope = {}) const;
ggml_backend_buffer_type_t params_buffer_type_for(const TensorState& state) const;
+ ggml_backend_buffer_type_t params_buffer_type_for(const TensorState& state, ggml_backend_t params_backend) const;
ggml_backend_buffer_type_t split_buffer_type_for(const TensorState& state) const;
- void release_compute_staging_blocks(bool force = false,
- const std::unordered_set<TensorState*>* target_states = nullptr);
- void release_params_storage_blocks(bool force = false,
- const std::unordered_set<TensorState*>* target_states = nullptr);
- void free_compute_staging_block(ComputeStagingBlock& block);
- void free_params_storage_block(ParamsStorageBlock& block);
- void erase_params_storage_block(ParamsStorageBlock* block);
- bool apply_resource_loras(Resource& resource, const std::vector<TensorState*>& states);
void reset_lora_applied_params(Resource& resource);
bool unregister_tensor_states(const std::unordered_set<TensorState*>& states, size_t* size, bool keep_registration = false);
size_t other_runtime_resident_bytes(uintptr_t owner_id,
@@ -248,13 +302,12 @@ private:
public:
~ModelManager() override;
+ void check_residency() const { store_.check_residency(); }
+
class ResourceHandle;
ResourceId create_resource();
bool remove_resource(ResourceId id);
- void set_retain_weights(bool retain) { retain_weights_ = retain; }
- bool retains_idle_weights() const override { return retain_weights_; }
- void release_idle_gpu_staging();
void set_max_vram(sd::ggml_graph_cut::MaxVramAssignment limit) { max_vram_ = std::move(limit); }
bool set_max_ram(size_t bytes);
const sd::ggml_graph_cut::MaxVramAssignment& max_vram() const { return max_vram_; }
@@ -390,8 +443,12 @@ public:
bool log_details = false) const override;
std::vector<WeightResidencyBlock> evictable_compute_backend_blocks(
ggml_backend_t backend,
- const std::vector<ggml_tensor*>& protected_params) const override;
- bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer = nullptr) override;
+ const std::vector<ggml_tensor*>& protected_params) const;
+ bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer = nullptr, const std::vector<ggml_tensor*>* protected_params = nullptr) override;
+ std::vector<WeightResidencyBlock> plan_reclaim(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) const override;
WeightPrefetchResult prefetch_params(
uintptr_t owner_id,
const std::vector<ggml_tensor*>& tensors) override;
@@ -421,7 +478,10 @@ public:
bool remove() { return manager_->remove_resource(id_); }
ResourceMemory memory() const { return manager_->resource_memory(resource()); }
- void set_layer_split(bool enabled) { resource().layer_split_ = enabled; }
+ void set_layer_split(bool enabled, std::vector<ggml_backend_t> backends = {}) {
+ resource().layer_split_ = enabled;
+ resource().layer_split_backends_ = enabled ? std::move(backends) : std::vector<ggml_backend_t>{};
+ }
bool place_params(ggml_backend_t backend, ResidencyMode mode) { return manager_->place_resource_params(resource(), backend, mode); }
const ModelLoader& loader() const { return resource().model_loader_; }
ModelLoader base_loader() const;
@@ -480,7 +540,6 @@ public:
std::shared_ptr<sd::ExecutionEngine> execution_engine() override { return manager_->execution_engine(); }
bool segmented_compute_enabled() const override { return !resource().segmented_compute_disabled_; }
bool prefetch_enabled() const override { return !resource().prefetch_disabled_; }
- bool retains_idle_weights() const override { return manager_->retains_idle_weights(); }
size_t context_vram_limit(ggml_backend_t backend) const override { return manager_->max_vram_bytes(backend); }
void register_runtime_owner(uintptr_t owner) override { manager_->register_runtime_owner(owner); }
void remove_runtime_owner(uintptr_t owner) override { manager_->remove_runtime_owner(owner); }
@@ -520,14 +579,16 @@ public:
bool log_details) const override {
return manager_->inspect_compute_backend_capacity(request, params, check, log_details);
}
- std::vector<WeightResidencyBlock> evictable_compute_backend_blocks(
- ggml_backend_t backend,
- const std::vector<ggml_tensor*>& protected_params) const override {
- return manager_->evictable_compute_backend_blocks(backend, protected_params);
+ bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer, const std::vector<ggml_tensor*>* protected_params) override {
+ return manager_->evict_compute_backend_block(block, prefetch_buffer, protected_params);
}
- bool evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer) override {
- return manager_->evict_compute_backend_block(block, prefetch_buffer);
+ std::vector<WeightResidencyBlock> plan_reclaim(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) const override {
+ return manager_->plan_reclaim(request, required_params, preferred_eviction_order, protected_params);
}
+
WeightPrefetchResult prefetch_params(uintptr_t owner, const std::vector<ggml_tensor*>& tensors) override {
return manager_->prefetch_params(owner, tensors);
}
diff --git a/src/model_manager_files.cpp b/src/model_manager_files.cpp
index 1846f47..f076e52 100644
--- a/src/model_manager_files.cpp
+++ b/src/model_manager_files.cpp
@@ -4,21 +4,7 @@
#include <string_view>
#include "core/util.h"
-
-static bool same_tensor_encoding(const TensorStorage& a, const TensorStorage& b) {
- return a.offset == b.offset && a.index_in_zip == b.index_in_zip &&
- a.storage_key == b.storage_key && a.type == b.type && a.expected_type == b.expected_type &&
- a.n_dims == b.n_dims && std::equal(a.ne, a.ne + SD_MAX_DIMS, b.ne) &&
- a.is_f8_e4m3 == b.is_f8_e4m3 && a.is_f8_e5m2 == b.is_f8_e5m2 &&
- a.is_f64 == b.is_f64 && a.is_i64 == b.is_i64 &&
- a.is_int8_tensorwise == b.is_int8_tensorwise && a.w4_convrot_kind == b.w4_convrot_kind && a.int8_convrot == b.int8_convrot &&
- a.int8_convrot_group_size == b.int8_convrot_group_size;
-}
-
-static bool same_tensor_source(const TensorStorage& a, const TensorStorage& b) {
- return a.file_id == b.file_id && a.file_revision == b.file_revision &&
- a.file_index == b.file_index && same_tensor_encoding(a, b);
-}
+#include "weights/sources.h"
ModelLoader ModelManager::ResourceHandle::base_loader() const {
const auto& source = resource();
@@ -40,26 +26,26 @@ ModelLoader::Dependencies ModelManager::ResourceHandle::dependencies() const {
void ModelManager::reuse_shared_weights(std::vector<TensorState*>& need_load) {
if (std::none_of(need_load.begin(), need_load.end(), [](const auto* state) {
- return !state->resource->shared_weights_key_.empty();
+ return !resource_of(*state).shared_weights_key_.empty();
}))
return;
std::map<std::pair<std::string_view, std::string_view>, std::vector<std::pair<TensorState*, ParamsStorageBlock*>>> resident;
auto group = [](const TensorState& state) -> std::string_view {
- return state.component == ModelComponent::LoRA ? std::string_view{} : state.resource->shared_weights_key_;
+ return state.component == ModelComponent::LoRA ? std::string_view{} : resource_of(state).shared_weights_key_;
};
std::map<TensorState*, ggml_tensor*> original_params;
- for (const auto& block : compute_staging_blocks_)
+ for (const auto& block : store_.compute_blocks())
for (const auto& [state, original] : block->staged_tensors)
original_params.emplace(state, original);
- for (const auto& block : params_storage_blocks_) {
+ for (const auto& block : store_.storage_blocks()) {
for (auto* state : block->states) {
- if (!state->resource->shared_weights_key_.empty() && !state->sources.empty())
+ if (!resource_of(*state).shared_weights_key_.empty() && !state->sources.empty())
resident[{group(*state), state->name}].emplace_back(state, block.get());
}
}
size_t reused = 0;
need_load.erase(std::remove_if(need_load.begin(), need_load.end(), [&](auto* state) {
- if (state->resource->shared_weights_key_.empty() || state->sources.empty() ||
+ if (resource_of(*state).shared_weights_key_.empty() || state->sources.empty() ||
state->tensor->view_src || split_buffer_type_for(*state))
return false;
const auto found = resident.find({group(*state), state->name});
@@ -74,24 +60,21 @@ void ModelManager::reuse_shared_weights(std::vector<TensorState*>& need_load) {
auto* tensor = candidate->tensor;
if (auto original = original_params.find(candidate); original != original_params.end())
tensor = original->second;
- if (!tensor->buffer || !tensor->data ||
- ggml_backend_buffer_get_type(tensor->buffer) != params_buffer_type_for(*state))
+ if (!tensor->buffer || !tensor->data)
continue;
- const auto& loader = source_loader(*state->resource, state->source_file);
- const auto& other = source_loader(*candidate->resource, candidate->source_file);
- if (!std::equal(state->sources.begin(), state->sources.end(),
- candidate->sources.begin(), candidate->sources.end(),
- [&](const TensorStorage& a, const TensorStorage& b) {
- return same_tensor_encoding(a, b) &&
- loader.same_weight_file(a.file_id, a.file_index, other, b.file_id, b.file_index);
- }))
+ // A copy anywhere on the sibling's residency chain serves it, as does a demoted
+ // copy that shares its compute backend.
+ const auto buft = ggml_backend_buffer_get_type(tensor->buffer);
+ bool usable = below_home(*block) && candidate->compute_backend == state->compute_backend;
+ for (auto backend = home_backend(*state); !usable && backend; backend = next_residency_backend(*state, backend))
+ usable = buft == params_buffer_type_for(*state, backend);
+ if (!usable)
continue;
- block->states.push_back(state);
- block->shared = true;
- state->tensor->buffer = tensor->buffer;
- state->tensor->data = tensor->data;
- state->tensor->extra = tensor->extra;
- state->loaded_to_params_backend = true;
+ const auto& loader = source_loader(resource_of(*state), state->source_file);
+ const auto& other = source_loader(resource_of(*candidate), candidate->source_file);
+ if (!sd::weights::same_weight(loader, state->sources, other, candidate->sources))
+ continue;
+ store_.share(*state, *block, *tensor, candidate->params_backend());
++reused;
return true;
}
@@ -102,49 +85,13 @@ void ModelManager::reuse_shared_weights(std::vector<TensorState*>& need_load) {
LOG_VERBOSE("model manager reused %zu resident weight tensors", reused);
}
-void ModelManager::detach_shared_weight(TensorState& state) {
- if (state.resource->shared_weights_key_.empty() || !state.loaded_to_params_backend ||
- state.staged_to_compute_backend || state.pin_count != 0)
- return;
- for (auto& block : params_storage_blocks_) {
- if (!block->shared || block->states.size() < 2)
- continue;
- auto found = std::find(block->states.begin(), block->states.end(), &state);
- if (found == block->states.end())
- continue;
- block->states.erase(found);
- state.tensor->buffer = nullptr;
- state.tensor->data = nullptr;
- state.tensor->extra = nullptr;
- state.loaded_to_params_backend = false;
- state.applied_lora_epoch = UINT64_MAX;
- return;
- }
-}
-
std::vector<TensorStorage> ModelManager::find_tensor_sources(const TensorState& state, const String2TensorStorage& sources) {
- auto first = sources.find(state.name);
- if (first == sources.end()) {
- return {};
- }
- std::vector<TensorStorage> result{first->second};
- if (state.component == ModelComponent::LoRA ||
- std::equal(first->second.ne, first->second.ne + GGML_MAX_DIMS, state.tensor->ne)) {
- return result;
- }
- for (size_t i = 1;; ++i) {
- auto part = sources.find(state.name + "." + std::to_string(i));
- if (part == sources.end()) {
- break;
- }
- result.push_back(part->second);
- }
- return result;
+ return sd::weights::find_sources(state.name, state.tensor->ne, state.component == ModelComponent::LoRA, sources);
}
void ModelManager::invalidate_sources(const std::unordered_set<TensorState*>& states) {
auto affected = states;
- for (const auto& block : params_storage_blocks_) {
+ for (const auto& block : store_.storage_blocks()) {
if (std::any_of(block->states.begin(), block->states.end(), [&](TensorState* state) { return states.count(state) != 0; })) {
affected.insert(block->states.begin(), block->states.end());
}
@@ -157,26 +104,26 @@ void ModelManager::invalidate_sources(const std::unordered_set<TensorState*>& st
++it;
}
}
- for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end();) {
- if (std::any_of((*it)->staged_tensors.begin(), (*it)->staged_tensors.end(), [&](const auto& entry) { return affected.count(entry.first) != 0; })) {
- ggml_backend_synchronize((*it)->compute_backend);
- free_compute_staging_block(**it);
- it = compute_staging_blocks_.erase(it);
- } else {
- ++it;
- }
+ std::vector<ComputeStagingBlock*> stale_compute;
+ for (const auto& block : store_.compute_blocks()) {
+ if (std::any_of(block->staged_tensors.begin(), block->staged_tensors.end(), [&](const auto& entry) { return affected.count(entry.first) != 0; }))
+ stale_compute.push_back(block.get());
}
- for (auto it = params_storage_blocks_.begin(); it != params_storage_blocks_.end();) {
- if (std::any_of((*it)->states.begin(), (*it)->states.end(), [&](TensorState* state) { return affected.count(state) != 0; })) {
- free_params_storage_block(**it);
- it = params_storage_blocks_.erase(it);
- } else {
- ++it;
- }
+ for (auto* block : stale_compute) {
+ ggml_backend_synchronize(block->compute_backend);
+ store_.release_compute(block);
+ }
+ std::vector<ParamsStorageBlock*> stale_storage;
+ for (const auto& block : store_.storage_blocks()) {
+ if (std::any_of(block->states.begin(), block->states.end(), [&](TensorState* state) { return affected.count(state) != 0; }))
+ stale_storage.push_back(block.get());
}
+ for (auto* block : stale_storage)
+ store_.release_storage(block, false);
for (auto* state : affected) {
state->metadata_validated = false;
- state->applied_lora_epoch = UINT64_MAX;
+ store_.reset_merges(*state);
+ store_.drop_merged_cache(*state);
}
}
@@ -201,8 +148,8 @@ size_t ModelManager::registered_params_size(const std::set<ModelComponent>& comp
}
bool ModelManager::set_loader(Resource& resource, ModelLoader loader) {
- if (!runtime_owners_.empty() || std::any_of(tensor_states_.begin(), tensor_states_.end(), [&](const auto& state) {
- return state->resource == &resource && state->pin_count != 0;
+ if (!runtime_owners_.empty() || std::any_of(store_.tensor_states().begin(), store_.tensor_states().end(), [&](const auto& state) {
+ return state->resource == &resource && state->pin_count() != 0;
})) {
LOG_ERROR("cannot update model sources during execution");
return false;
@@ -225,13 +172,12 @@ bool ModelManager::set_loader(Resource& resource, ModelLoader loader) {
lora_changed |= loader.file_revision(spec.file_id) != spec.file_revision;
}
std::unordered_set<TensorState*> changed;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource != &resource)
continue;
const auto sources = find_tensor_sources(*state, sources_for(*state));
- if (sources.size() != state->sources.size() ||
- !std::equal(sources.begin(), sources.end(), state->sources.begin(), same_tensor_source) ||
- (lora_changed && state->component != ModelComponent::LoRA && state->applied_lora_epoch != UINT64_MAX)) {
+ if (!sd::weights::same_sources(sources, state->sources) ||
+ (lora_changed && state->component != ModelComponent::LoRA && state->applied_epoch() != UINT64_MAX)) {
changed.insert(state.get());
}
}
@@ -241,6 +187,11 @@ bool ModelManager::set_loader(Resource& resource, ModelLoader loader) {
}
if (lora_changed) {
++resource.current_lora_epoch_;
+ for (auto& state : store_.tensor_states()) {
+ if (state->resource == &resource) {
+ store_.drop_merged_cache(*state);
+ }
+ }
for (auto& spec : resource.loras_)
spec.file_revision = loader.file_revision(spec.file_id);
}
@@ -277,7 +228,7 @@ ModelLoader::FileVersions ModelManager::source_versions(const std::set<ModelComp
const auto& resource = default_resource_;
ModelLoader::FileVersions versions;
const auto& sources = loader.get_tensor_storage_map();
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource != &resource || components.count(state->component) == 0) {
continue;
}
@@ -297,7 +248,7 @@ ModelLoader::FileVersions ModelManager::source_versions(const std::set<ModelComp
size_t ModelManager::registered_params_size(const Resource& resource, const std::set<ModelComponent>& components) const {
size_t bytes = 0;
std::unordered_set<const ggml_tensor*> seen;
- for (const auto& state : tensor_states_) {
+ for (const auto& state : store_.tensor_states()) {
if (state->resource == &resource && components.count(state->component) != 0 && state->tensor != nullptr && seen.insert(state->tensor).second) {
bytes += ggml_nbytes(state->tensor);
}
@@ -327,7 +278,7 @@ ModelLoader::FileId ModelManager::register_model_source(Resource& resource, Mode
}
bool ModelManager::unregister_model_source(Resource& resource, ModelLoader::FileId file) {
- if (std::any_of(tensor_states_.begin(), tensor_states_.end(), [&](const auto& state) {
+ if (std::any_of(store_.tensor_states().begin(), store_.tensor_states().end(), [&](const auto& state) {
return state->resource == &resource && state->source_file == file;
})) {
LOG_ERROR("cannot unregister a model source while its weights are registered");
diff --git a/src/model_manager_prefetch.cpp b/src/model_manager_prefetch.cpp
index bc27837..46c7ec3 100644
--- a/src/model_manager_prefetch.cpp
+++ b/src/model_manager_prefetch.cpp
@@ -1,47 +1,16 @@
#include "model_manager.h"
#include <algorithm>
+#include <map>
+#include <unordered_set>
#include <utility>
#include "core/ggml_extend_backend.h"
#include "core/util.h"
#include "ggml-alloc.h"
-ggml_backend_t ModelManager::prefetch_backend_for(ggml_backend_t compute_backend) {
- auto existing = prefetch_backends_.find(compute_backend);
- if (existing != prefetch_backends_.end()) {
- return existing->second;
- }
- if (compute_backend == nullptr) {
- return nullptr;
- }
-
- ggml_backend_dev_t device = ggml_backend_get_device(compute_backend);
- if (device == nullptr || ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_CPU) {
- return nullptr;
- }
- ggml_backend_t transfer_backend = ggml_backend_dev_init(device, nullptr);
- if (transfer_backend == nullptr) {
- LOG_WARN("model manager failed to create a prefetch backend for %s",
- ggml_backend_name(compute_backend));
- }
- prefetch_backends_[compute_backend] = transfer_backend;
- return transfer_backend;
-}
-
-void ModelManager::synchronize_prefetch_block(PrefetchBlock& block) {
- if (block.event != nullptr) {
- ggml_backend_event_synchronize(block.event);
- ggml_backend_event_free(block.event);
- block.event = nullptr;
- } else if (block.submitted && block.transfer_backend != nullptr) {
- ggml_backend_synchronize(block.transfer_backend);
- }
- block.transfer_backend = nullptr;
-}
-
void ModelManager::free_prefetch_block(PrefetchBlock& block) {
- synchronize_prefetch_block(block);
+ sd::weights::WeightTransfer::wait(block.transfer);
for (auto& staging_block : block.staging_blocks) {
if (staging_block == nullptr) {
continue;
@@ -59,21 +28,27 @@ void ModelManager::free_prefetch_block(PrefetchBlock& block) {
block.staging_blocks.clear();
}
+const ggml_tensor* ModelManager::prefetch_source(const PrefetchBlock& block, const TensorState& state) {
+ const auto merged = block.merged.find(&state);
+ return merged != block.merged.end() ? &merged->second->tensor : state.tensor;
+}
+
bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer* prefetch_buffer) {
if (block.states.empty() || block.compute_backend == nullptr) {
return false;
}
- block.transfer_backend = prefetch_backend_for(block.compute_backend);
- if (block.transfer_backend == nullptr) {
+ block.transfer.queue = transfer_.queue_for(block.compute_backend);
+ if (block.transfer.queue == nullptr) {
return false;
}
for (TensorState* state : block.states) {
- if (state == nullptr || state->tensor == nullptr ||
- state->tensor->buffer == nullptr || state->tensor->data == nullptr ||
- state->params_backend == nullptr || state->staged_to_compute_backend ||
- state->pin_count > 0) {
+ if (state == nullptr || state->tensor == nullptr || state->staged() || state->pin_count() > 0)
+ return false;
+ const auto* source = prefetch_source(block, *state);
+ if (source->buffer == nullptr || source->data == nullptr ||
+ (source == state->tensor && state->params_backend() == nullptr)) {
return false;
}
}
@@ -95,7 +70,7 @@ bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer*
backend_limit = MAX_RESIDENCY_BLOCK_BYTES;
}
const bool reuse_buffer = prefetch_buffer != nullptr && prefetch_buffer->buffer;
- if (reuse_buffer || (retain_weights_ && host_capacity)) {
+ if (reuse_buffer || host_capacity) {
size_t bytes = 0;
for (const auto* state : block.states) {
const auto padded = GGML_PAD(ggml_backend_buft_get_alloc_size(buffer_type, state->tensor), alignment);
@@ -104,7 +79,7 @@ bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer*
if (reuse_buffer && (prefetch_buffer->type != buffer_type || prefetch_buffer->bytes != bytes || bytes > backend_limit)) {
return false;
}
- if (retain_weights_ && host_capacity &&
+ if (host_capacity &&
!ensure_host_capacity(host_buffer ? bytes : 0, block.states, host_buffer, host_buffer || reuse_buffer ? 0 : bytes)) {
return false;
}
@@ -130,9 +105,10 @@ bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer*
for (TensorState* state : chunk) {
ggml_tensor* staging_tensor = ggml_dup_tensor(staging_ctx, state->tensor);
ggml_set_name(staging_tensor, state->tensor->name);
- if (ggml_backend_buffer_is_host(state->tensor->buffer) &&
- (!ggml_is_contiguous(state->tensor) || !ggml_is_contiguous(staging_tensor) ||
- ggml_nbytes(state->tensor) != ggml_nbytes(staging_tensor))) {
+ const auto* source = prefetch_source(block, *state);
+ if (ggml_backend_buffer_is_host(source->buffer) &&
+ (!ggml_is_contiguous(source) || !ggml_is_contiguous(staging_tensor) ||
+ ggml_nbytes(source) != ggml_nbytes(staging_tensor))) {
ggml_free(staging_ctx);
staging_block->staging_ctx = nullptr;
return false;
@@ -190,35 +166,19 @@ bool ModelManager::populate_prefetch_block(PrefetchBlock& block, PrefetchBuffer*
void ModelManager::submit_prefetched_params(uintptr_t owner_id) {
auto existing = prefetch_blocks_.find(owner_id);
- if (existing == prefetch_blocks_.end() || existing->second->submitted) {
+ if (existing == prefetch_blocks_.end() || existing->second->transfer.submitted) {
return;
}
- auto& block = *existing->second;
- block.submitted = true;
+ auto& block = *existing->second;
+ std::vector<sd::weights::WeightTransfer::Copy> copies;
for (const auto& staging_block : block.staging_blocks) {
- for (const auto& pair : staging_block->staged_tensors) {
- TensorState* state = pair.first;
- ggml_tensor* staging_tensor = pair.second;
- if (ggml_backend_buffer_is_host(state->tensor->buffer)) {
- ggml_backend_tensor_set_async(block.transfer_backend,
- staging_tensor,
- state->tensor->data,
- 0,
- ggml_nbytes(state->tensor));
- } else {
- ggml_backend_tensor_copy_async(state->params_backend,
- block.transfer_backend,
- state->tensor,
- staging_tensor);
- }
+ for (const auto& [state, staging_tensor] : staging_block->staged_tensors) {
+ copies.push_back({prefetch_source(block, *state), state->params_backend(), staging_tensor});
+ if (block.merged.count(state) == 0)
+ block.source_epochs[state] = state->loaded() ? state->storage_epoch() : UINT64_MAX;
}
}
-
- ggml_backend_dev_t device = ggml_backend_get_device(block.transfer_backend);
- block.event = ggml_backend_event_new(device);
- if (block.event != nullptr) {
- ggml_backend_event_record(block.event, block.transfer_backend);
- }
+ transfer_.submit(block.transfer, copies);
size_t total_size = 0;
for (const auto& staging_block : block.staging_blocks) {
@@ -258,6 +218,8 @@ WeightPrefetchResult ModelManager::prepare_prefetch_params(
std::vector<TensorState*> states;
states.reserve(required_states.size());
+ const std::unordered_set<TensorState*> requested(required_states.begin(), required_states.end());
+ std::map<const TensorState*, std::shared_ptr<const CachedLoraWeight>> merged;
ggml_backend_t compute_backend = nullptr;
bool needs_synchronous_load = false;
for (TensorState* state : required_states) {
@@ -265,17 +227,22 @@ WeightPrefetchResult ModelManager::prepare_prefetch_params(
is_optional_missing_tensor(state->name)) {
continue;
}
- if (has_lora_int8_pair(*state)) {
- // Synchronous staging keeps the merged weight and scale in the same block.
- needs_synchronous_load = needs_synchronous_load || !state->staged_to_compute_backend;
+ // An INT8 weight and its scale upload together, so both carry the same merge.
+ const bool cached = reusable_lora_weight(*state) &&
+ (!has_lora_int8_pair(*state) || requested.count(state->lora_int8_partner) != 0);
+ if (cached) {
+ if (!state->staged() && state->pin_count() == 0)
+ merged.emplace(state, state->cached_lora());
+ } else if (has_lora_int8_pair(*state) || state->param_source() == ParamSource::ModelFile) {
+ // These weights are restored by synchronous staging, including the LoRA state.
+ needs_synchronous_load = needs_synchronous_load || !state->staged();
continue;
- }
- if (state->usage_op == GGML_OP_CUSTOM || state->compute_backend == state->params_backend) {
+ } else if (state->usage_op == GGML_OP_CUSTOM || state->compute_backend == state->params_backend()) {
needs_synchronous_load = needs_synchronous_load ||
- !state->loaded_to_params_backend;
+ !state->loaded();
continue;
}
- if (state->staged_to_compute_backend || state->pin_count > 0) {
+ if (state->staged() || state->pin_count() > 0) {
continue;
}
// Split buffers cannot use the primary device's asynchronous upload path.
@@ -306,13 +273,19 @@ WeightPrefetchResult ModelManager::prepare_prefetch_params(
return WeightPrefetchResult::Unsupported;
}
clear_prefetched_params(owner_id);
- if (!load_tensors_to_params_backend(states)) {
+ std::vector<TensorState*> originals;
+ for (auto* state : states) {
+ if (merged.count(state) == 0)
+ originals.push_back(state);
+ }
+ if (!load_tensors_to_params_backend(originals)) {
return WeightPrefetchResult::Failed;
}
auto block = std::make_unique<PrefetchBlock>();
block->states = std::move(states);
block->compute_backend = compute_backend;
+ block->merged = std::move(merged);
if (!populate_prefetch_block(*block, prefetch_buffer)) {
free_prefetch_block(*block);
return WeightPrefetchResult::Failed;
@@ -333,12 +306,14 @@ bool ModelManager::activate_prefetched_params(
required_states.begin(),
required_states.end(),
[&](TensorState* state) {
- return state == nullptr || should_ignore(*state) ||
- is_optional_missing_tensor(state->name) ||
- has_lora_int8_pair(*state) ||
+ if (state == nullptr || should_ignore(*state) || is_optional_missing_tensor(state->name) || state->staged())
+ return true;
+ if (reusable_lora_weight(*state))
+ return false;
+ return has_lora_int8_pair(*state) ||
+ state->param_source() == ParamSource::ModelFile ||
state->usage_op == GGML_OP_CUSTOM ||
- state->compute_backend == state->params_backend ||
- state->staged_to_compute_backend;
+ state->compute_backend == state->params_backend();
});
if (already_staged) {
clear_prefetched_params(owner_id);
@@ -352,7 +327,7 @@ bool ModelManager::activate_prefetched_params(
submit_prefetched_params(owner_id);
std::unique_ptr<PrefetchBlock> block = std::move(existing->second);
prefetch_blocks_.erase(existing);
- synchronize_prefetch_block(*block);
+ sd::weights::WeightTransfer::wait(block->transfer);
for (const auto& staging_block : block->staging_blocks) {
if (staging_block == nullptr) {
@@ -361,8 +336,11 @@ bool ModelManager::activate_prefetched_params(
for (const auto& pair : staging_block->staged_tensors) {
TensorState* state = pair.first;
ggml_tensor* staging_tensor = pair.second;
+ const auto source = block->source_epochs.find(state);
+ const bool stale = source != block->source_epochs.end() &&
+ source->second != (state->loaded() ? state->storage_epoch() : UINT64_MAX);
if (state == nullptr || state->tensor == nullptr || staging_tensor == nullptr ||
- state->staged_to_compute_backend || state->pin_count > 0) {
+ state->staged() || state->pin_count() > 0 || stale) {
free_prefetch_block(*block);
return false;
}
@@ -373,16 +351,23 @@ bool ModelManager::activate_prefetched_params(
if (staging_block == nullptr) {
continue;
}
+ // An uploaded copy carries the merge of its source.
+ std::vector<uint64_t> epochs;
for (auto& pair : staging_block->staged_tensors) {
TensorState* state = pair.first;
ggml_tensor* staging_tensor = pair.second;
std::swap(state->tensor->buffer, staging_tensor->buffer);
std::swap(state->tensor->data, staging_tensor->data);
std::swap(state->tensor->extra, staging_tensor->extra);
- state->staged_to_compute_backend = true;
- state->last_use_epoch = use_epoch;
+ const auto merged = block->merged.find(state);
+ const auto source = block->source_epochs.find(state);
+ epochs.push_back(merged != block->merged.end() ? merged->second->lora_epoch
+ : source != block->source_epochs.end() ? source->second
+ : state->loaded() ? state->storage_epoch()
+ : UINT64_MAX);
+ state->last_use_epoch = use_epoch;
}
- compute_staging_blocks_.push_back(std::move(staging_block));
+ store_.add_compute(std::move(staging_block), epochs);
}
block->staging_blocks.clear();
return true;
@@ -407,10 +392,5 @@ void ModelManager::clear_all_prefetched_params() {
void ModelManager::release_prefetch() {
clear_all_prefetched_params();
- for (auto& entry : prefetch_backends_) {
- if (entry.second != nullptr) {
- ggml_backend_free(entry.second);
- }
- }
- prefetch_backends_.clear();
+ transfer_.release();
}
diff --git a/src/model_manager_prepare.cpp b/src/model_manager_prepare.cpp
new file mode 100644
index 0000000..249a295
--- /dev/null
+++ b/src/model_manager_prepare.cpp
@@ -0,0 +1,440 @@
+#include "model_manager.h"
+
+#include <algorithm>
+#include <deque>
+#include <map>
+#include <set>
+#include <unordered_set>
+#include <utility>
+
+#include "core/ggml_extend_backend.h"
+#include "core/util.h"
+#include "model/adapter/lora_merge.h"
+
+// Weight preparation: loads and stages a graph's weights, merges pending LoRA versions into the
+// 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) {
+ if (tensors.empty())
+ return true;
+ std::vector<TensorState*> states;
+ if (!resolve_required_tensor_states(tensors, states))
+ return false;
+ 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;
+ }
+ }
+ if (states.empty())
+ return true;
+
+ std::map<ggml_backend_t, std::vector<TensorState*>> by_compute;
+ for (auto* state : states) {
+ if (state->compute_backend && !sd_backend_is_cpu(state->compute_backend))
+ by_compute[state->compute_backend].push_back(state);
+ }
+ for (const auto& [backend, group] : by_compute)
+ place_first_loads({backend}, group);
+
+ std::map<Resource*, sd::lora::MergeProgress> merge_progress;
+ const MergeFn merge = [&](const std::vector<TensorState*>& request, bool& capacity_failure, std::string& capacity_error) {
+ std::map<Resource*, std::vector<MergeUnit>> by_resource;
+ for (const auto& unit : pending_merges(request))
+ by_resource[&resource_of(*unit.target)].push_back(unit);
+ for (auto& [resource, group] : by_resource) {
+ // Nested preparation inside the merge graph does not merge this resource again.
+ struct Applying {
+ Resource& resource;
+ ~Applying() { resource.applying_loras_ = false; }
+ } applying{*resource};
+ resource->applying_loras_ = true;
+ std::vector<sd::lora::MergeCandidate> candidates;
+ std::vector<TensorState*> owners;
+ if (!merge_candidates(*resource, group, candidates, owners))
+ return false;
+ if (candidates.empty())
+ continue;
+ const auto names = tensor_names(*resource);
+ std::vector<size_t> merged;
+ auto& progress = merge_progress[resource];
+ const bool ok = sd::lora::merge_candidates(resource->loras_, candidates, merge_context(*resource, names),
+ progress, merged, capacity_failure);
+ for (const auto& entry : progress) {
+ if (!entry.second.capacity_error.empty())
+ capacity_error = entry.second.capacity_error;
+ }
+ std::vector<TensorState*> committed;
+ for (auto index : merged)
+ committed.push_back(owners[index]);
+ commit_merged(committed, resource->current_lora_epoch_);
+ if (!ok)
+ return false;
+ }
+ return true;
+ };
+
+ // 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.
+ if (!ensure_copies(states)) {
+ release_unprepared(states);
+ return false;
+ }
+
+ // Merge pending LoRA versions, then commit them on the copies written. The merge leases the
+ // request's weights, so its own reclaim cannot release them. The leases pass to the caller only
+ // on success; a failure or an exception releases them and drops copies the merge may have written.
+ const uint64_t use_epoch = lease_states(states);
+ struct Leases {
+ ModelManager& manager;
+ const std::vector<TensorState*>& states;
+ bool held = true;
+ ~Leases() {
+ if (!held)
+ return;
+ manager.finish_compute_backend_usage(states);
+ manager.abandon_merge(states);
+ }
+ } leases{*this, states};
+#ifndef NDEBUG
+ std::vector<bool> ready_before;
+ for (const auto* state : states)
+ ready_before.push_back(ready_for_compute(*state));
+#endif
+ bool capacity_failure = false;
+ std::string capacity_error;
+ bool merged = merge(states, capacity_failure, capacity_error);
+#ifndef NDEBUG
+ // Leased weights survive the merge's own reclaim.
+ for (size_t i = 0; merged && i < states.size(); ++i)
+ GGML_ASSERT(!ready_before[i] || ready_for_compute(*states[i]));
+#endif
+ if (!merged && capacity_failure) {
+ std::vector<TensorState*> yielding;
+ for (auto* state : states) {
+ if (!state->staged() && !lora_merge_target(*state))
+ yielding.push_back(state);
+ }
+ if (!yielding.empty()) {
+ finish_compute_backend_usage(yielding);
+ struct RestoreLeases {
+ ModelManager& manager;
+ const std::vector<TensorState*>& states;
+ uint64_t epoch;
+ ~RestoreLeases() { manager.lease_states(states, epoch); }
+ } restore{*this, yielding, use_epoch};
+ capacity_failure = false;
+ capacity_error.clear();
+ merged = merge(states, capacity_failure, capacity_error) && ensure_copies(states);
+ }
+ }
+ if (!merged && capacity_failure) {
+ // The request's copies and one merge graph do not fit on the device together. Start again
+ // from the originals and merge a batch of targets at a time with only that batch leased.
+ leases.held = false;
+ finish_compute_backend_usage(states);
+ abandon_merge(states);
+ const MergeFn merge_fresh = [&](const auto& batch, bool& failed, std::string& error) {
+ merge_progress.clear();
+ return merge(batch, failed, error);
+ };
+ if (!merge_in_batches(states, merge_fresh))
+ return false;
+ lease_states(states, use_epoch);
+ leases.held = true;
+ if (const auto* missing = unmerged_weight(states)) {
+ LOG_ERROR(
+ "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;
+ }
+ } else if (!merged) {
+ return false;
+ }
+ leases.held = false;
+ check_residency();
+ return true;
+}
+
+bool 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);
+ const auto* previous_spills = lora_batch_spills_;
+ std::unordered_set<TensorState*> spills;
+ if (previous_spills)
+ spills = *previous_spills;
+ for (auto* state : states) {
+ if (lora_merge_target(*state))
+ spills.insert(state);
+ }
+ struct SpillScope {
+ ModelManager& manager;
+ const std::unordered_set<TensorState*>& weights;
+ const std::unordered_set<TensorState*>* previous;
+ ~SpillScope() {
+ manager.lora_batch_spills_ = previous;
+ for (auto* state : weights) {
+ if (state->residency_mode == ResidencyMode::Disk && (!previous || !previous->count(state)))
+ manager.store_.drop_merged_cache(*state);
+ }
+ }
+ } spill_scope{*this, spills, previous_spills};
+ lora_batch_spills_ = &spills;
+ // Batches start at the update size one merge graph takes by default and split in half while
+ // their leased copies and the merge graph still do not fit.
+ const size_t limit = sd::lora::GroupProgress{}.batch_bytes;
+ std::deque<std::pair<size_t, size_t>> batches;
+ size_t batch_bytes = 0;
+ for (size_t index = 0; index < units.size(); ++index) {
+ const size_t update = size_t(ggml_nelements(units[index].target->tensor)) * sizeof(float);
+ if (batches.empty() || batch_bytes + update > limit) {
+ batches.emplace_back(index, index);
+ batch_bytes = 0;
+ }
+ batches.back().second = index + 1;
+ batch_bytes += update;
+ }
+ // 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)) {
+ release_unprepared(batch);
+ if (capacity_failure)
+ capacity_error = "staging the batch's weights does not fit in device memory";
+ return false;
+ }
+ lease_states(batch);
+ struct BatchLeases {
+ ModelManager& manager;
+ const std::vector<TensorState*>& batch;
+ bool merged = false;
+ ~BatchLeases() {
+ manager.finish_compute_backend_usage(batch);
+ if (!merged)
+ manager.abandon_merge(batch);
+ }
+ } leases{*this, batch};
+ leases.merged = merge(batch, capacity_failure, capacity_error);
+ return leases.merged;
+ };
+ LOG_INFO("merging immediate LoRA in batches to fit device memory (%zu targets)", units.size());
+ while (!batches.empty()) {
+ const auto [first, end] = batches.front();
+ batches.pop_front();
+ std::vector<TensorState*> batch;
+ batch.reserve(end - first);
+ for (size_t index = first; index < end; ++index) {
+ batch.push_back(units[index].target);
+ 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))
+ continue;
+ if (!capacity_failure)
+ return false;
+ if (end - first == 1) {
+ LOG_ERROR("immediate LoRA does not fit in device memory: %s", capacity_error.c_str());
+ return false;
+ }
+ const size_t middle = first + (end - first) / 2;
+ batches.emplace_front(middle, end);
+ batches.emplace_front(first, middle);
+ LOG_INFO("merging immediate LoRA %zu targets at a time", middle - first);
+ }
+ return ensure_copies(states);
+}
+
+const ModelManager::TensorState* ModelManager::unmerged_weight(const std::vector<TensorState*>& states) const {
+ for (const auto* state : states) {
+ if (state != nullptr && merge_pending(*state))
+ return state;
+ }
+ return nullptr;
+}
+
+bool ModelManager::lora_merge_target(const TensorState& state) const {
+ const auto& resource = resource_of(state);
+ if (state.tensor == nullptr || state.component == ModelComponent::LoRA || resource.loras_.empty() ||
+ should_ignore(state) || (state.sources.empty() && is_optional_missing_tensor(state.name)))
+ return false;
+ if (needs_lora_staging(state))
+ return true;
+ // Shared weights merge only into separate compute copies; the rest merge in place.
+ if (!resource.shared_weights_key_.empty() || state.component == ModelComponent::LatentUpsampler ||
+ resource.model_sources_.count(state.source_file) != 0)
+ return false;
+ return !state.is_int8_weight || resource.lora_targets_.count(state.name) != 0;
+}
+
+bool ModelManager::merge_pending(const TensorState& state) const {
+ const auto& resource = resource_of(state);
+ // A nested preparation inside the merge graph leaves the resource being merged alone.
+ return !resource.applying_loras_ && state.applied_epoch() != resource.current_lora_epoch_ && lora_merge_target(state);
+}
+
+std::vector<ModelManager::MergeUnit> ModelManager::pending_merges(const std::vector<TensorState*>& states) const {
+ const std::unordered_set<const TensorState*> requested(states.begin(), states.end());
+ std::vector<MergeUnit> units;
+ for (auto* state : states) {
+ if (state == nullptr || !merge_pending(*state))
+ continue;
+ auto* partner = has_lora_int8_pair(*state) ? state->lora_int8_partner : nullptr;
+ if (partner && !state->is_int8_weight && requested.count(partner) != 0 && merge_pending(*partner))
+ continue;
+ units.push_back({state, state->is_int8_weight && partner && merge_pending(*partner) ? partner : nullptr});
+ }
+ return units;
+}
+
+bool ModelManager::ready_for_compute(const TensorState& state) const {
+ if (should_ignore(state) || (state.sources.empty() && is_optional_missing_tensor(state.name)) || state.staged())
+ return true;
+ if (state.tensor->view_src) {
+ // A view reads the copy of the weight it views.
+ const ggml_tensor* root = state.tensor;
+ while (root->view_src)
+ root = root->view_src;
+ const auto viewed = store_.tensor_index().find(root);
+ return state.tensor->data && (viewed == store_.tensor_index().end() || viewed->second == &state ||
+ ready_for_compute(*viewed->second));
+ }
+ return state.tensor->data && !needs_lora_staging(state) &&
+ (state.usage_op == GGML_OP_CUSTOM ||
+ (state.param_source() == ParamSource::Backend && state.compute_backend == state.params_backend()));
+}
+
+bool ModelManager::ensure_copies(const std::vector<TensorState*>& states, bool* capacity_failure) {
+ // 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) ||
+ !stage_tensors_to_compute_backend(states, staging_capacity) || !ensure_host_capacity(0, states)) {
+ if (capacity_failure)
+ *capacity_failure = load_capacity || staging_capacity;
+ return false;
+ }
+ if (std::all_of(states.begin(), states.end(), [&](const TensorState* state) { return ready_for_compute(*state); }))
+ return true;
+ }
+ for (const auto* state : states) {
+ if (!ready_for_compute(*state)) {
+ LOG_ERROR("model manager could not prepare weight '%s' for %s", state->name.c_str(),
+ state->compute_backend ? ggml_backend_name(state->compute_backend) : "compute");
+ break;
+ }
+ }
+ return false;
+}
+
+void ModelManager::release_unprepared(const std::vector<TensorState*>& states) {
+ const std::unordered_set<TensorState*> failed(states.begin(), states.end());
+ store_.release_compute_staging_blocks(false, &failed);
+ store_.release_params_storage_blocks(false, &failed);
+}
+
+uint64_t ModelManager::lease_states(const std::vector<TensorState*>& states, uint64_t use_epoch) {
+ if (use_epoch == 0)
+ use_epoch = ++residency_epoch_;
+ for (auto* state : states) {
+ store_.lease(*state);
+ state->last_use_epoch = use_epoch;
+ }
+ return use_epoch;
+}
+
+void ModelManager::abandon_merge(const std::vector<TensorState*>& states) {
+ // A failed merge may have written compute copies and, for weights merged in place, their
+ // storage copies. Both kinds are dropped so the next merge starts from the originals.
+ std::unordered_set<TensorState*> staged, in_place;
+ for (auto* state : states) {
+ if (state->staged())
+ staged.insert(state);
+ else if (!needs_lora_staging(*state) && merge_pending(*state))
+ in_place.insert(state);
+ }
+ if (!staged.empty() && !store_.discard_lora_staging(staged)) {
+ invalidate_sources({states.begin(), states.end()});
+ return;
+ }
+ if (!in_place.empty())
+ invalidate_sources(in_place);
+}
+
+bool ModelManager::merge_candidates(Resource& resource,
+ const std::vector<MergeUnit>& units,
+ std::vector<sd::lora::MergeCandidate>& candidates,
+ std::vector<TensorState*>& owners) {
+ for (const auto& unit : units) {
+ for (auto* state : {unit.target, unit.scale}) {
+ if (!state)
+ continue;
+ // Selection is done; only the copies the merge writes are checked here.
+ if (needs_lora_staging(*state) && !state->staged())
+ return false;
+ if (state->compute_backend == nullptr) {
+ LOG_ERROR("model manager compute backend is null for lora target tensor '%s'", state->name.c_str());
+ return false;
+ }
+ if (state->tensor->buffer != nullptr &&
+ ggml_backend_buffer_get_type(state->tensor->buffer) == split_buffer_type_for(*state)) {
+ if (!resource.warned_split_lora_skip_) {
+ LOG_WARN(
+ "model manager skipping direct lora application to row-split tensors "
+ "(use --lora-apply-mode at_runtime with row split)");
+ resource.warned_split_lora_skip_ = true;
+ }
+ store_.mark_merged(*state, resource.current_lora_epoch_);
+ continue;
+ }
+ if (state->tensor->data == nullptr) {
+ LOG_ERROR("model manager lora target tensor '%s' is not prepared", state->name.c_str());
+ return false;
+ }
+ sd::lora::MergeCandidate candidate;
+ candidate.name = state->name;
+ candidate.tensor = state->tensor;
+ candidate.compute_backend = state->compute_backend;
+ candidate.params_backend = state->preferred_backend;
+ candidate.residency = state->residency_mode;
+ if (state->is_int8_weight) {
+ if (!state->lora_int8_partner || !state->lora_int8_partner->staged()) {
+ LOG_ERROR("model manager INT8 LoRA target '%s' has no staged weight scale", state->name.c_str());
+ return false;
+ }
+ const auto& storage = state->sources.front();
+ candidate.int8_scale = state->lora_int8_partner->tensor;
+ candidate.convrot_group_size = storage.int8_convrot ? storage.int8_convrot_group_size : 0;
+ } else if (has_lora_int8_pair(*state)) {
+ candidate.scale_only = true;
+ }
+ candidates.push_back(std::move(candidate));
+ owners.push_back(state);
+ }
+ }
+ return true;
+}
+
+sd::lora::MergeContext ModelManager::merge_context(Resource& resource, const std::set<std::string>& model_tensor_names) {
+ sd::lora::MergeContext context;
+ context.version = resource.lora_version_;
+ context.n_threads = resource.n_threads_;
+ context.model_tensor_names = &model_tensor_names;
+ const auto id = resource.id;
+ context.adapter_weights = [this, id] {
+ // Adapter weights stay in this manager's residency; the borrowed owner outlives the merge.
+ auto borrowed_manager = std::shared_ptr<ModelManager>(this, [](ModelManager*) {});
+ return std::make_shared<ResourceHandle>(std::move(borrowed_manager), id);
+ };
+ return context;
+}
+
+void ModelManager::commit_merged(const std::vector<TensorState*>& states, uint64_t epoch) {
+ for (auto* state : states)
+ store_.mark_merged(*state, epoch);
+}
diff --git a/src/model_manager_reclaim.cpp b/src/model_manager_reclaim.cpp
new file mode 100644
index 0000000..bdf714e
--- /dev/null
+++ b/src/model_manager_reclaim.cpp
@@ -0,0 +1,476 @@
+#include "model_manager.h"
+
+#include <algorithm>
+#include <map>
+#include <set>
+#include <unordered_map>
+#include <unordered_set>
+
+#include "core/ggml_extend_backend.h"
+#include "core/util.h"
+#include "weights/capacity.h"
+#include "weights/reclaim_planner.h"
+#include "weights/weight_copy.h"
+
+using sd::weights::copy_weights;
+using sd::weights::weight_copy_bytes;
+using HostWeightCopies = sd::weights::WeightCopies;
+
+// Reclaim: the allocation snapshot the planner orders, and the execution of its actions through the
+// store. A move that needs room at its target makes that room with release-only reclaim, so a
+// nested reclaim never moves another copy.
+
+sd::weights::Snapshot ModelManager::residency_snapshot(const sd::weights::Request& plan, ggml_backend_t backend) const {
+ using namespace sd::weights;
+ const auto tier = plan.tier;
+ Snapshot snapshot;
+ std::unordered_set<TensorState*> prefetched;
+ protect_prefetched_states(prefetched);
+ const bool host = tier == Tier::Host;
+ const auto device = backend ? ggml_backend_get_device(backend) : nullptr;
+ auto in_tier = [&](ggml_backend_buffer_t buffer) {
+ if (buffer == nullptr || ggml_backend_buffer_is_host(buffer) != host)
+ return false;
+ if (host)
+ return true;
+ const auto type = ggml_backend_buffer_get_type(buffer);
+ const auto split = split_buffer_devices_.find(type);
+ if (split != split_buffer_devices_.end()) {
+ return std::any_of(split->second.begin(), split->second.end(), [&](const auto& entry) {
+ return ggml_backend_get_device(entry.first) == device;
+ });
+ }
+ return ggml_backend_buft_get_device(type) == device;
+ };
+ auto copy_of = [&](TensorState* state) {
+ Copy copy;
+ copy.weight = reinterpret_cast<WeightId>(state);
+ copy.resource = reinterpret_cast<ResourceId>(state->resource);
+ copy.next_use = next_weight_use(*state);
+ copy.last_use = state->last_use_epoch;
+ copy.leased = state->pin_count() != 0;
+ copy.prefetched = prefetched.count(state) != 0;
+ copy.shared = !resource_of(*state).shared_weights_key_.empty();
+ return copy;
+ };
+ for (const auto& block : store_.compute_blocks()) {
+ if (!in_tier(block->buffer) || block->staged_tensors.empty())
+ continue;
+ Allocation allocation{reinterpret_cast<uintptr_t>(block->buffer), tier, AllocationKind::Compute,
+ ggml_backend_buffer_get_size(block->buffer)};
+ for (const auto& entry : block->staged_tensors) {
+ if (auto* state = entry.first) {
+ allocation.copies.push_back(copy_of(state));
+ if (host && preserves_batch_merge(*state))
+ allocation.fixed = true;
+ }
+ }
+ snapshot.allocations.push_back(std::move(allocation));
+ }
+ for (const auto& block : store_.storage_blocks()) {
+ if (!in_tier(block->buffer) || block->states.empty())
+ continue;
+ Allocation allocation{reinterpret_cast<uintptr_t>(block->buffer), tier, AllocationKind::Storage,
+ ggml_backend_buffer_get_size(block->buffer)};
+ // Loader-retained mappings cannot be reclaimed by freeing a device block.
+ allocation.fixed = !host && !block->mmap_tensor_stores.empty();
+ // A block still being filled holds no copy yet; it stays until its read completes or rolls back.
+ allocation.fixed |= std::any_of(block->states.begin(), block->states.end(),
+ [&](const TensorState* state) { return state && state->storage_copy() != block.get(); });
+ for (auto* state : block->states) {
+ if (!state)
+ continue;
+ auto copy = copy_of(state);
+ copy.movable = !state->sources.empty() && !state->tensor->view_src &&
+ (host || (!state->split_buffer_type && state->usage_op != GGML_OP_CUSTOM));
+ if (host) {
+ // A compute copy no longer reads its RAM original. A merge applied in place cannot be reread.
+ copy.superseded = state->staged();
+ copy.movable &= copy.superseded || state->applied_epoch() == UINT64_MAX;
+ } else {
+ // A device original only feeds a separate merged copy, and the adapter weights of an
+ // immediate LoRA only feed merges; the merge reloads them when needed.
+ const bool adapter = state->component == ModelComponent::LoRA && !resource_of(*state).loras_.empty() &&
+ state->pin_count() == 0 && !plan.required.count(copy.weight);
+ copy.superseded = adapter || (needs_lora_staging(*state) && (state->staged() || state->pin_count() == 0));
+ copy.leased = copy.leased || (state->staged() && !copy.superseded);
+ copy.has_lower_location = next_residency_backend(*state, state->params_backend()) != nullptr;
+ if (!copy.has_lower_location && !state->staged() && preserves_batch_merge(*state))
+ copy.movable = false;
+ // The reload allocates with the device's padding and alignment.
+ if (plan.required.count(copy.weight))
+ copy.reload_bytes = compute_backend_alloc_size({state}, false);
+ }
+ allocation.copies.push_back(copy);
+ }
+ snapshot.allocations.push_back(std::move(allocation));
+ }
+ if (host) {
+ std::map<ggml_backend_buffer_t, Allocation> caches;
+ for (const auto& state : store_.tensor_states()) {
+ if (!state->cached_lora())
+ continue;
+ const auto buffer = state->cached_lora()->tensor.buffer;
+ auto& allocation = caches[buffer];
+ allocation.id = reinterpret_cast<uintptr_t>(buffer);
+ allocation.tier = Tier::Host;
+ allocation.kind = AllocationKind::MergedCache;
+ allocation.bytes = ggml_backend_buffer_get_size(buffer);
+ allocation.fixed |= lora_batch_spills_ && lora_batch_spills_->count(state.get());
+ auto copy = copy_of(state.get());
+ // A staged weight already holds its merged copy on the device.
+ copy.superseded = state->staged();
+ copy.leased = false;
+ allocation.copies.push_back(copy);
+ }
+ for (auto& entry : caches)
+ snapshot.allocations.push_back(std::move(entry.second));
+ }
+ return snapshot;
+}
+
+bool ModelManager::evict_host_weight_block(const std::unordered_set<TensorState*>& protected_states,
+ const sd::weights::PriorityLimit* limit) {
+ sd::weights::Request request;
+ request.tier = sd::weights::Tier::Host;
+ request.priority_limit = limit;
+ for (auto* state : protected_states)
+ request.protected_weights.insert(reinterpret_cast<sd::weights::WeightId>(state));
+ const auto actions = sd::weights::plan_reclaim(residency_snapshot(request, nullptr), request);
+ if (actions.empty())
+ return false;
+ const auto& action = actions.front();
+ const auto buffer = reinterpret_cast<ggml_backend_buffer_t>(action.allocation);
+ for (auto& state : store_.tensor_states()) {
+ if (state->cached_lora() && state->cached_lora()->tensor.buffer == buffer) {
+ LOG_DEBUG("model manager evicted %.2f MiB of merged LoRA weights from RAM", action.bytes / (1024.0 * 1024.0));
+ for (auto& other : store_.tensor_states()) {
+ if (other->cached_lora() && other->cached_lora()->tensor.buffer == buffer)
+ store_.drop_merged_cache(*other);
+ }
+ return true;
+ }
+ }
+ for (auto it = store_.compute_blocks().begin(); it != store_.compute_blocks().end(); ++it) {
+ if ((*it)->buffer == buffer) {
+ LOG_VERBOSE("model manager evicted %.2f MiB of staged weights on %s for RAM",
+ action.bytes / (1024.0 * 1024.0), ggml_backend_name((*it)->compute_backend));
+ store_.release_compute(it->get());
+ return true;
+ }
+ }
+ for (const auto& block : store_.storage_blocks()) {
+ if (block->buffer == buffer) {
+ LOG_VERBOSE("model manager evicted %.2f MiB of weight storage from RAM", action.bytes / (1024.0 * 1024.0));
+ // A compute copy no longer needs its RAM original; a later restage reads the model file.
+ const bool staged = std::any_of(block->states.begin(), block->states.end(),
+ [](const auto* state) { return state->staged(); });
+ store_.free_params_storage_block(*block, staged);
+ store_.erase_params_storage_block(block.get());
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ModelManager::demote_params_storage_block(ParamsStorageBlock* block, const std::vector<TensorState*>& protected_states) {
+ if (!block || !block->buffer || ggml_backend_buffer_is_host(block->buffer) || !block->mmap_tensor_stores.empty() ||
+ block->states.empty()) {
+ return false;
+ }
+ std::unordered_set<TensorState*> prefetched;
+ protect_prefetched_states(prefetched);
+ auto* first = block->states.front();
+ const auto device = first->params_backend() ? ggml_backend_get_device(first->params_backend()) : nullptr;
+ for (auto* state : block->states) {
+ // Active merged copies do not read their originals.
+ const bool merge_source = state->staged() && needs_lora_staging(*state);
+ if ((state->pin_count() != 0 && !merge_source) || prefetched.count(state) || state->sources.empty() || !state->params_backend() ||
+ ggml_backend_get_device(state->params_backend()) != device || state->split_buffer_type ||
+ state->tensor->view_src || state->usage_op == GGML_OP_CUSTOM) {
+ return false;
+ }
+ }
+ const auto from = first->params_backend();
+ for (auto target = next_residency_backend(*first, from); target; target = next_residency_backend(*first, target)) {
+ if (copy_params_storage_block(*block, target, protected_states)) {
+ return true;
+ }
+ }
+ if (std::any_of(block->states.begin(), block->states.end(), [&](auto* state) {
+ return !state->staged() && preserves_batch_merge(*state);
+ }))
+ return false;
+ LOG_VERBOSE("model manager released %.2f MiB of weights from %s; they reload from the model file",
+ ggml_backend_buffer_get_size(block->buffer) / (1024.0 * 1024.0), ggml_backend_name(from));
+ store_.free_params_storage_block(*block, true);
+ store_.erase_params_storage_block(block);
+ return true;
+}
+
+bool ModelManager::copy_params_storage_block(ParamsStorageBlock& block,
+ ggml_backend_t target,
+ const std::vector<TensorState*>& protected_states) {
+ std::unordered_map<TensorState*, ggml_tensor*> originals;
+ for (const auto& staging : store_.compute_blocks()) {
+ for (const auto& [state, original] : staging->staged_tensors) {
+ originals.emplace(state, original);
+ }
+ }
+ std::map<const void*, ggml_tensor> moved;
+ HostWeightCopies copies, bindings;
+ size_t next_use = planned_next_use_.empty() ? 0 : SIZE_MAX;
+ uint64_t last_use = 0;
+ for (auto* state : block.states) {
+ auto* original = state->tensor;
+ if (state->staged()) {
+ const auto found = originals.find(state);
+ if (found == originals.end()) {
+ return false;
+ }
+ original = found->second;
+ }
+ if (original->buffer != block.buffer || !original->data) {
+ return false;
+ }
+ auto [entry, inserted] = moved.try_emplace(original->data, *original);
+ if (original->type != entry->second.type || !ggml_are_same_shape(original, &entry->second) ||
+ !std::equal(original->nb, original->nb + GGML_MAX_DIMS, entry->second.nb)) {
+ return false;
+ }
+ if (inserted) {
+ copies.emplace_back(original, &entry->second);
+ }
+ bindings.emplace_back(original, &entry->second);
+ next_use = std::min(next_use, next_weight_use(*state));
+ last_use = std::max(last_use, state->last_use_epoch);
+ }
+ auto* first = block.states.front();
+ const auto buft = params_buffer_type_for(*first, target);
+ if (!buft) {
+ return false;
+ }
+ const size_t bytes = weight_copy_bytes(buft, copies);
+ if (bytes == SIZE_MAX) {
+ return false;
+ }
+ auto protected_list = protected_states;
+ protected_list.insert(protected_list.end(), block.states.begin(), block.states.end());
+ const bool host = ggml_backend_buft_is_host(buft);
+ {
+ bool fits = false;
+ if (host) {
+ const sd::weights::PriorityLimit limit{next_use, last_use};
+ fits = ensure_host_capacity(bytes, protected_list, true, 0, true, &limit);
+ } else {
+ std::vector<ggml_tensor*> protected_params;
+ protected_params.reserve(protected_list.size());
+ for (auto* state : protected_list) {
+ protected_params.push_back(state->tensor);
+ }
+ DeviceMemoryRequest request{target, 0, bytes};
+ request.quiet = true;
+ request.release_only = true;
+ fits = ensure_device_capacity(request, {}, {}, protected_params);
+ }
+ if (!fits) {
+ return false;
+ }
+ }
+ auto buffer = copy_weights(buft, first->compute_backend, copies, bytes);
+ if (!buffer) {
+ return false;
+ }
+ // Change all aliases and saved staging bindings before returning the source allocation.
+ for (const auto& [original, destination] : bindings) {
+ original->buffer = destination->buffer;
+ original->data = destination->data;
+ original->extra = destination->extra;
+ }
+ const auto source = first->params_backend();
+ LOG_VERBOSE("model manager moved %.2f MiB of weights from %s to %s",
+ bytes / (1024.0 * 1024.0), ggml_backend_name(source), host ? "RAM" : ggml_backend_name(target));
+ store_.replace_storage_buffer(block, buffer.release(), target);
+ return true;
+}
+
+void ModelManager::evict_compute_backend_params(const std::vector<ggml_tensor*>& tensors) {
+ std::unordered_set<TensorState*> targets;
+ std::set<ggml_backend_t> backends;
+ // Session cleanup may follow unregistration, after tensor metadata has been freed.
+ for (auto* tensor : tensors) {
+ const auto found = store_.tensor_index().find(tensor);
+ if (found != store_.tensor_index().end() && found->second->compute_backend) {
+ targets.insert(found->second);
+ backends.insert(found->second->compute_backend);
+ }
+ }
+ // Compute copies of weights stored elsewhere end with the session, as do disk-resident weights.
+ for (auto backend : backends) {
+ for (const auto& candidate : reclaim_candidates(backend, make_reclaim_request(backend, false))) {
+ std::vector<TensorState*> states;
+ for (auto* tensor : candidate.tensors)
+ states.push_back(store_.tensor_index().at(tensor));
+ if (std::none_of(states.begin(), states.end(), [&](auto* state) { return targets.count(state) != 0; }))
+ continue;
+ const bool staging = std::any_of(store_.compute_blocks().begin(), store_.compute_blocks().end(),
+ [&](const auto& block) { return block->buffer == candidate.buffer; });
+ const bool ends = std::all_of(states.begin(), states.end(), [&](auto* state) {
+ return staging ? !prefers_compute_residency(*state) : state->residency_mode == ResidencyMode::Disk;
+ });
+ if (ends)
+ evict_compute_backend_block(candidate);
+ }
+ }
+ std::unordered_set<TensorState*> protected_states;
+ protect_prefetched_states(protected_states);
+ for (auto* state : targets) {
+ if (state->cached_lora() && state->residency_mode == ResidencyMode::Disk && state->pin_count() == 0 &&
+ !protected_states.count(state))
+ store_.drop_merged_cache(*state);
+ }
+}
+
+sd::weights::Request ModelManager::make_reclaim_request(ggml_backend_t backend,
+ bool allow_moves,
+ const std::vector<TensorState*>& required,
+ const std::vector<TensorState*>& protected_list,
+ const ReclaimScope& scope) {
+ sd::weights::Request plan;
+ plan.tier = sd_backend_is_cpu(backend) ? sd::weights::Tier::Host : sd::weights::Tier::Device;
+ plan.allow_moves = allow_moves;
+ plan.keep_resources = scope.keep_resources;
+ plan.keep_next_use = scope.keep_next_use;
+ for (auto* state : required)
+ plan.required.insert(reinterpret_cast<sd::weights::WeightId>(state));
+ for (auto* state : protected_list)
+ plan.protected_weights.insert(reinterpret_cast<sd::weights::WeightId>(state));
+ return plan;
+}
+
+std::vector<WeightResidencyBlock> ModelManager::reclaim_candidates(ggml_backend_t backend, const sd::weights::Request& plan) const {
+ std::vector<WeightResidencyBlock> result;
+ const auto actions = sd::weights::plan_reclaim(residency_snapshot(plan, backend), plan);
+ result.reserve(actions.size());
+ for (const auto& action : actions)
+ result.push_back(reclaim_block(action, backend));
+ return result;
+}
+
+size_t ModelManager::reclaimable_bytes(const DeviceMemoryRequest& request,
+ ggml_backend_t backend,
+ const std::vector<TensorState*>& required,
+ const std::vector<TensorState*>& protected_list,
+ const ReclaimScope& scope) const {
+ if (backend == nullptr)
+ return 0;
+ const auto plan = make_reclaim_request(backend, !request.release_only, required, protected_list, scope);
+ return sd::weights::reclaimable_bytes(residency_snapshot(plan, backend), plan);
+}
+
+WeightResidencyBlock ModelManager::reclaim_block(const sd::weights::Action& action, ggml_backend_t backend) {
+ WeightResidencyBlock block;
+ block.buffer = reinterpret_cast<ggml_backend_buffer_t>(action.allocation);
+ block.backend = backend;
+ block.bytes = action.bytes;
+ block.restage_bytes = action.reload_bytes;
+ block.action = action.kind == sd::weights::ActionKind::Move ? ReclaimAction::Move
+ : action.kind == sd::weights::ActionKind::Release ? ReclaimAction::Release
+ : ReclaimAction::Drop;
+ for (auto weight : action.weights)
+ block.tensors.push_back(reinterpret_cast<TensorState*>(weight)->tensor);
+ return block;
+}
+
+std::vector<WeightResidencyBlock> ModelManager::evictable_compute_backend_blocks(
+ ggml_backend_t backend,
+ const std::vector<ggml_tensor*>& protected_params) const {
+ return plan_reclaim({backend}, {}, {}, protected_params);
+}
+
+std::vector<WeightResidencyBlock> ModelManager::plan_reclaim(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) const {
+ std::vector<TensorState*> required, protected_list;
+ if (!request.compute_backend || !resolve_required_tensor_states(required_params, required) ||
+ !resolve_required_tensor_states(protected_params, protected_list)) {
+ return {};
+ }
+ protected_list.insert(protected_list.end(), required.begin(), required.end());
+ if (request.reloadable_params) {
+ std::vector<TensorState*> reloadable;
+ if (!resolve_required_tensor_states(*request.reloadable_params, reloadable))
+ return {};
+ required.insert(required.end(), reloadable.begin(), reloadable.end());
+ }
+ auto plan = make_reclaim_request(request.compute_backend, !request.release_only, required, protected_list);
+ for (size_t index = 0; index < preferred_eviction_order.size(); ++index) {
+ for (auto* tensor : preferred_eviction_order[index]) {
+ const auto found = store_.tensor_index().find(resolve_param_tensor(tensor));
+ if (found != store_.tensor_index().end())
+ plan.positions.emplace(reinterpret_cast<sd::weights::WeightId>(found->second), index);
+ }
+ }
+ return reclaim_candidates(request.compute_backend, plan);
+}
+
+bool ModelManager::evict_compute_backend_block(const WeightResidencyBlock& block, PrefetchBuffer* prefetch_buffer, const std::vector<ggml_tensor*>* protected_params) {
+ for (auto it = store_.compute_blocks().begin(); it != store_.compute_blocks().end(); ++it) {
+ if ((*it)->buffer != block.buffer)
+ continue;
+ if (std::any_of((*it)->staged_tensors.begin(), (*it)->staged_tensors.end(),
+ [](const auto& entry) { return entry.first && entry.first->pin_count() != 0; }))
+ return false;
+ LOG_DEBUG("model manager evicted %.2f MiB of staged weights on %s",
+ block.bytes / (1024.0 * 1024.0), ggml_backend_name(block.backend));
+ if (!cache_merged_lora_weights(**it))
+ return false;
+ // The old weights are unpinned. Hand the allocation to the next upload before it can enter the idle pool.
+ const bool hand_off = prefetch_buffer != nullptr && !prefetch_buffer->buffer && prefetch_buffer->bytes == block.bytes &&
+ prefetch_buffer->type == ggml_backend_buffer_get_type(block.buffer);
+ auto* kept = store_.release_compute(it->get(), hand_off);
+ if (hand_off)
+ prefetch_buffer->buffer.reset(kept);
+ return true;
+ }
+ for (auto it = store_.storage_blocks().begin(); it != store_.storage_blocks().end(); ++it) {
+ if ((*it)->buffer != block.buffer)
+ continue;
+ LOG_DEBUG("model manager evicted %.2f MiB of weight storage on %s",
+ block.bytes / (1024.0 * 1024.0), ggml_backend_name(block.backend));
+ if (std::any_of((*it)->states.begin(), (*it)->states.end(), [](const auto* state) {
+ return state->pin_count() != 0 && !(state->staged() && needs_lora_staging(*state));
+ }))
+ return false;
+ if (block.action == ReclaimAction::Drop)
+ return false;
+ if (block.action == ReclaimAction::Release) {
+ if (std::any_of((*it)->states.begin(), (*it)->states.end(), [&](auto* state) {
+ return !state->staged() && preserves_batch_merge(*state);
+ }))
+ return false;
+ const bool merge_sources = std::any_of((*it)->states.begin(), (*it)->states.end(),
+ [](const auto* state) { return state->staged(); });
+ if (!ggml_backend_buffer_is_host((*it)->buffer))
+ LOG_VERBOSE("model manager released %.2f MiB of weights from %s; they reload from the model file",
+ block.bytes / (1024.0 * 1024.0), ggml_backend_name(block.backend));
+ store_.release_storage(it->get(), merge_sources || !ggml_backend_buffer_is_host((*it)->buffer));
+ return true;
+ }
+ std::vector<TensorState*> keep;
+ for (auto* tensor : protected_params ? *protected_params : std::vector<ggml_tensor*>{}) {
+ for (auto* current = tensor; current; current = current->view_src) {
+ const auto found = store_.tensor_index().find(current);
+ if (found == store_.tensor_index().end())
+ continue;
+ keep.push_back(found->second);
+ if (found->second->lora_int8_partner)
+ keep.push_back(found->second->lora_int8_partner);
+ break;
+ }
+ }
+ return demote_params_storage_block(it->get(), keep);
+ }
+ return false;
+}
diff --git a/src/weights/accounting.cpp b/src/weights/accounting.cpp
new file mode 100644
index 0000000..99e9538
--- /dev/null
+++ b/src/weights/accounting.cpp
@@ -0,0 +1,61 @@
+#include "weights/accounting.h"
+
+#include <algorithm>
+
+namespace sd::weights {
+ DeviceMemoryCapacity evaluate_capacity(const CapacityDemand& demand, const std::vector<DeviceSnapshot>& devices) {
+ auto add = [](size_t a, size_t b) { return b > SIZE_MAX - a ? SIZE_MAX : a + b; };
+ DeviceMemoryCapacity result;
+ result.devices.reserve(devices.size());
+ result.pools.reserve(devices.size());
+ const size_t pending = add(demand.pending_runtime, demand.missing_weights);
+ const size_t allocation = pending - std::min(pending, demand.reused_allocation);
+ // WDDM can report zero free memory even after all buffers for the graph have been allocated.
+ result.required_device_bytes = allocation == 0 ? 0 : add(allocation, demand.safety_margin);
+ result.required_budget_bytes = add(add(demand.resident_runtime, demand.pending_runtime), demand.missing_weights);
+ for (const auto& device : devices) {
+ auto& headroom = result.devices.emplace_back();
+ headroom.backend = device.backend;
+ const size_t reclaimable = demand.reclaim ? std::min(device.reclaimable, device.weights_resident) : 0;
+ const size_t resident = add(device.weights_resident - reclaimable, device.other_runtime);
+ result.pools.push_back({device.device, device.backend, device.pool_accounted, device.free_bytes, device.total_bytes,
+ device.pool_bytes, device.limit, resident});
+ size_t free_bytes = device.free_bytes;
+ size_t total_bytes = device.total_bytes;
+ size_t pool_bytes = device.pool_bytes;
+ if (demand.reclaim && pool_bytes > 0) {
+ free_bytes = device.free_without_pool;
+ total_bytes = device.total_without_pool;
+ pool_bytes = 0;
+ }
+ const size_t committed = add(resident, pool_bytes);
+ if (device.limit > 0) {
+ result.requires_reclamation |= committed > device.limit;
+ headroom.overcommitted = committed > device.limit ? committed - device.limit : 0;
+ headroom.available_budget = device.limit - std::min(device.limit, committed);
+ result.overcommitted_bytes = std::max(result.overcommitted_bytes, headroom.overcommitted);
+ result.available_budget_bytes = std::min(result.available_budget_bytes, headroom.available_budget);
+ }
+ if (free_bytes == 0 && total_bytes == 0)
+ continue;
+ if (total_bytes > 0 && free_bytes > total_bytes && device.vulkan) {
+ if (!device.integrated) {
+ result.available_device_bytes = 0;
+ headroom.available_device = 0;
+ continue;
+ }
+ // Integrated GPUs fall back to tracked residency, after a reclaim confirms it.
+ free_bytes = total_bytes;
+ result.wrapped_device_report = true;
+ }
+ free_bytes = add(free_bytes, reclaimable);
+ if (total_bytes > 0) {
+ const size_t used = add(committed, add(demand.resident_runtime, demand.reused_allocation));
+ free_bytes = std::min(free_bytes, used < total_bytes ? total_bytes - used : 0);
+ }
+ result.available_device_bytes = std::min(result.available_device_bytes, free_bytes);
+ headroom.available_device = free_bytes;
+ }
+ return result;
+ }
+}
diff --git a/src/weights/accounting.h b/src/weights/accounting.h
new file mode 100644
index 0000000..321f34f5
--- /dev/null
+++ b/src/weights/accounting.h
@@ -0,0 +1,49 @@
+#ifndef __SD_WEIGHTS_ACCOUNTING_H__
+#define __SD_WEIGHTS_ACCOUNTING_H__
+
+#include <cstddef>
+#include <vector>
+
+#include "device_residency_manager.h"
+
+namespace sd::weights {
+ // Memory of one device as a capacity query sees it.
+ struct DeviceSnapshot {
+ ggml_backend_t backend = nullptr;
+ ggml_backend_dev_t device = nullptr;
+ size_t weights_resident = 0;
+ size_t other_runtime = 0;
+ // Net bytes the reclaim plan frees on this device.
+ size_t reclaimable = 0;
+ // Budget limit; 0 means none.
+ size_t limit = 0;
+ // The backend reports the bytes its idle buffer pool retains.
+ bool pool_accounted = false;
+ size_t free_bytes = 0;
+ size_t total_bytes = 0;
+ size_t pool_bytes = 0;
+ // Device memory after returning the pool, for queries that count it as reclaimable.
+ size_t free_without_pool = 0;
+ size_t total_without_pool = 0;
+ // Vulkan subtracts its heap budget and can report more free memory than exists.
+ bool vulkan = false;
+ bool integrated = false;
+ };
+
+ struct CapacityDemand {
+ // Bytes of the request's weights that are not on the device yet.
+ size_t missing_weights = 0;
+ size_t pending_runtime = 0;
+ size_t resident_runtime = 0;
+ size_t reused_allocation = 0;
+ // Backend scratch buffers and pipelines are not included in graph measurements.
+ size_t safety_margin = 0;
+ // Counts the reclaim plan and the idle pool as free.
+ bool reclaim = false;
+ };
+
+ // The capacity of the devices for the demand. Pure: the same snapshot gives the same answer.
+ DeviceMemoryCapacity evaluate_capacity(const CapacityDemand& demand, const std::vector<DeviceSnapshot>& devices);
+}
+
+#endif // __SD_WEIGHTS_ACCOUNTING_H__
diff --git a/src/weights/capacity.h b/src/weights/capacity.h
new file mode 100644
index 0000000..05dc70f
--- /dev/null
+++ b/src/weights/capacity.h
@@ -0,0 +1,25 @@
+#ifndef __SD_WEIGHTS_CAPACITY_H__
+#define __SD_WEIGHTS_CAPACITY_H__
+
+#include <string>
+#include <vector>
+
+#include "device_residency_manager.h"
+
+namespace sd::weights {
+ // Device memory the residency layer needs before it allocates weight copies. The runtime
+ // implements it: it sums weights, workspaces and buffer pools, and executes the residency
+ // layer's reclaim plan to make room. The residency layer never calls the runtime otherwise.
+ class CapacityProvider {
+ public:
+ virtual ~CapacityProvider() = default;
+ // required: weights the allocation is for; protected_params stay through the reclaim.
+ virtual bool 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) = 0;
+ };
+}
+
+#endif // __SD_WEIGHTS_CAPACITY_H__
diff --git a/src/weights/reclaim_planner.cpp b/src/weights/reclaim_planner.cpp
new file mode 100644
index 0000000..a4a8875
--- /dev/null
+++ b/src/weights/reclaim_planner.cpp
@@ -0,0 +1,139 @@
+#include "weights/reclaim_planner.h"
+
+#include <algorithm>
+
+namespace sd::weights {
+ namespace {
+ bool contains(const std::unordered_set<WeightId>& set, WeightId weight) {
+ return set.find(weight) != set.end();
+ }
+
+ // Returns false when the allocation must stay for this request.
+ bool describe(const Allocation& allocation, const Request& request, Action& action) {
+ if (allocation.fixed || allocation.copies.empty() || allocation.tier != request.tier)
+ return false;
+ action.allocation = allocation.id;
+ action.bytes = allocation.bytes;
+ action.next_use = SIZE_MAX;
+ action.position = 0;
+ action.merge_source = allocation.kind == AllocationKind::Storage && allocation.tier == Tier::Device;
+ bool lower = false;
+ bool kept = false;
+ for (const auto& copy : allocation.copies) {
+ const bool required = contains(request.required, copy.weight);
+ const bool guarded = copy.leased || required || contains(request.protected_weights, copy.weight);
+ if (copy.prefetched)
+ return false;
+ if (allocation.kind == AllocationKind::Storage) {
+ if (!copy.movable)
+ return false;
+ if (!copy.superseded) {
+ action.merge_source = false;
+ if (guarded) {
+ // A required weight that is not in use yet can load again after the action.
+ if (copy.leased || !required || allocation.tier != Tier::Device)
+ return false;
+ action.reload_bytes += copy.reload_bytes;
+ }
+ }
+ } else if (guarded && !copy.superseded) {
+ return false;
+ }
+ lower |= copy.has_lower_location;
+ kept |= request.keep_resources && request.keep_resources->count(copy.resource) != 0;
+ action.shared |= copy.shared;
+ action.next_use = std::min(action.next_use, copy.next_use);
+ action.last_use = std::max(action.last_use, copy.last_use);
+ const auto position = request.positions.find(copy.weight);
+ action.position = position == request.positions.end() || action.position == SIZE_MAX
+ ? SIZE_MAX
+ : std::max(action.position, position->second);
+ action.weights.push_back(copy.weight);
+ }
+ if (allocation.kind == AllocationKind::Storage)
+ action.kind = lower && request.allow_moves ? ActionKind::Move : ActionKind::Release;
+ else
+ action.kind = ActionKind::Drop;
+ if (action.net_bytes() == 0)
+ return false;
+ // A first load keeps resident originals its scope names, whether they would move down
+ // or return to the model file.
+ if (action.kind != ActionKind::Drop && !action.merge_source && request.keep_resources &&
+ (kept || action.next_use < request.keep_next_use))
+ return false;
+ if (request.priority_limit && !request.priority_limit->allows(action.next_use, action.last_use))
+ return false;
+ return !request.filter || request.filter(allocation);
+ }
+
+ bool device_before(const Action& lhs, const Action& rhs) {
+ // Device originals of merged weights hold nothing the current LoRA version reads.
+ if (lhs.merge_source != rhs.merge_source)
+ return lhs.merge_source;
+ if (lhs.next_use != rhs.next_use)
+ return lhs.next_use > rhs.next_use;
+ if ((lhs.reload_bytes == 0) != (rhs.reload_bytes == 0))
+ return lhs.reload_bytes == 0;
+ const bool lhs_move = lhs.kind == ActionKind::Move, rhs_move = rhs.kind == ActionKind::Move;
+ if (lhs_move != rhs_move)
+ return !lhs_move;
+ if ((lhs.position == SIZE_MAX) != (rhs.position == SIZE_MAX))
+ return lhs.position == SIZE_MAX;
+ if (!lhs_move) {
+ if (lhs.position != rhs.position)
+ return lhs.position < rhs.position;
+ if (lhs.position != SIZE_MAX)
+ return false;
+ }
+ return lhs.last_use < rhs.last_use;
+ }
+
+ bool host_before(const Action& lhs, const Action& rhs, bool lhs_cache, bool rhs_cache, bool lhs_compute, bool rhs_compute) {
+ // Merged caches can be rebuilt from their originals, so they go before weights.
+ if (lhs_cache != rhs_cache)
+ return lhs_cache;
+ if (lhs_cache)
+ return lhs.last_use < rhs.last_use;
+ if (lhs.next_use != rhs.next_use)
+ return lhs.next_use > rhs.next_use;
+ const bool lhs_shared = lhs_compute && lhs.shared, rhs_shared = rhs_compute && rhs.shared;
+ if (lhs_shared != rhs_shared)
+ return lhs_shared;
+ return lhs.last_use < rhs.last_use;
+ }
+ }
+
+ std::vector<Action> plan_reclaim(const Snapshot& snapshot, const Request& request) {
+ std::vector<Action> actions;
+ std::unordered_map<uintptr_t, AllocationKind> kinds;
+ for (const auto& allocation : snapshot.allocations) {
+ Action action;
+ if (describe(allocation, request, action)) {
+ kinds[allocation.id] = allocation.kind;
+ actions.push_back(std::move(action));
+ }
+ }
+ if (request.tier == Tier::Device) {
+ std::stable_sort(actions.begin(), actions.end(), device_before);
+ } else {
+ std::stable_sort(actions.begin(), actions.end(), [&](const Action& lhs, const Action& rhs) {
+ const auto lhs_kind = kinds.at(lhs.allocation), rhs_kind = kinds.at(rhs.allocation);
+ return host_before(lhs, rhs, lhs_kind == AllocationKind::MergedCache, rhs_kind == AllocationKind::MergedCache,
+ lhs_kind == AllocationKind::Compute, rhs_kind == AllocationKind::Compute);
+ });
+ }
+ return actions;
+ }
+
+ size_t reclaimable_bytes(const Snapshot& snapshot, const Request& request) {
+ size_t bytes = 0;
+ for (const auto& allocation : snapshot.allocations) {
+ Action action;
+ if (!describe(allocation, request, action))
+ continue;
+ const size_t net = action.net_bytes();
+ bytes = net > SIZE_MAX - bytes ? SIZE_MAX : bytes + net;
+ }
+ return bytes;
+ }
+}
diff --git a/src/weights/reclaim_planner.h b/src/weights/reclaim_planner.h
new file mode 100644
index 0000000..480b917
--- /dev/null
+++ b/src/weights/reclaim_planner.h
@@ -0,0 +1,71 @@
+#ifndef __SD_WEIGHTS_RECLAIM_PLANNER_H__
+#define __SD_WEIGHTS_RECLAIM_PLANNER_H__
+
+#include <functional>
+#include <unordered_map>
+#include <unordered_set>
+#include <vector>
+
+#include "weights/state.h"
+
+namespace sd::weights {
+ enum class ActionKind {
+ // Free a copy that has another copy or the model file below it.
+ Drop,
+ // Copy to the next residency location, then free.
+ Move,
+ // Free the only copy above the model file.
+ Release,
+ };
+
+ struct Action {
+ uintptr_t allocation = 0;
+ ActionKind kind = ActionKind::Drop;
+ size_t bytes = 0;
+ // Bytes of the request's own weights that load again after the action.
+ size_t reload_bytes = 0;
+ // Only device originals whose merged copies are separate.
+ bool merge_source = false;
+ size_t next_use = 0;
+ uint64_t last_use = 0;
+ size_t position = SIZE_MAX;
+ bool shared = false;
+ std::vector<WeightId> weights;
+
+ size_t net_bytes() const { return bytes - (reload_bytes < bytes ? reload_bytes : bytes); }
+ };
+
+ // Victims for a demotion must have a lower priority than the weights moving in.
+ struct PriorityLimit {
+ size_t next_use = 0;
+ uint64_t last_use = 0;
+
+ bool allows(size_t next, uint64_t last) const { return next > next_use || (next == next_use && last < last_use); }
+ };
+
+ struct Request {
+ Tier tier = Tier::Device;
+ // Weights the request uses. Device copies may leave when the caller loads them again.
+ std::unordered_set<WeightId> required;
+ // Weights that stay, except superseded copies.
+ std::unordered_set<WeightId> protected_weights;
+ // Victims are released instead of copied further, e.g. while making room for a move.
+ bool allow_moves = true;
+ // A first load keeps resident originals of these resources and those needed sooner,
+ // against both moves and releases.
+ const std::unordered_set<ResourceId>* keep_resources = nullptr;
+ size_t keep_next_use = 0;
+ const PriorityLimit* priority_limit = nullptr;
+ // Position of a weight in the caller's preferred eviction order.
+ std::unordered_map<WeightId, size_t> positions;
+ // Restricts the actions, e.g. to copies that end with a session.
+ std::function<bool(const Allocation&)> filter;
+ };
+
+ // Actions in execution order.
+ std::vector<Action> plan_reclaim(const Snapshot& snapshot, const Request& request);
+ // The net bytes of the same actions; eligibility does not depend on their order.
+ size_t reclaimable_bytes(const Snapshot& snapshot, const Request& request);
+}
+
+#endif // __SD_WEIGHTS_RECLAIM_PLANNER_H__
diff --git a/src/weights/sources.cpp b/src/weights/sources.cpp
new file mode 100644
index 0000000..b77a440
--- /dev/null
+++ b/src/weights/sources.cpp
@@ -0,0 +1,49 @@
+#include "weights/sources.h"
+
+#include <algorithm>
+
+namespace sd::weights {
+ std::vector<TensorStorage> find_sources(const std::string& name,
+ const int64_t* registered_ne,
+ bool single_tensor,
+ const String2TensorStorage& sources) {
+ auto first = sources.find(name);
+ if (first == sources.end())
+ return {};
+ std::vector<TensorStorage> result{first->second};
+ if (single_tensor || std::equal(first->second.ne, first->second.ne + GGML_MAX_DIMS, registered_ne))
+ return result;
+ for (size_t i = 1;; ++i) {
+ auto part = sources.find(name + "." + std::to_string(i));
+ if (part == sources.end())
+ break;
+ result.push_back(part->second);
+ }
+ return result;
+ }
+
+ bool same_encoding(const TensorStorage& a, const TensorStorage& b) {
+ return a.offset == b.offset && a.index_in_zip == b.index_in_zip && a.storage_key == b.storage_key && a.type == b.type &&
+ a.expected_type == b.expected_type && a.n_dims == b.n_dims && std::equal(a.ne, a.ne + SD_MAX_DIMS, b.ne) &&
+ a.is_f8_e4m3 == b.is_f8_e4m3 && a.is_f8_e5m2 == b.is_f8_e5m2 && a.is_f64 == b.is_f64 && a.is_i64 == b.is_i64 &&
+ a.is_int8_tensorwise == b.is_int8_tensorwise && a.w4_convrot_kind == b.w4_convrot_kind &&
+ a.int8_convrot == b.int8_convrot && a.int8_convrot_group_size == b.int8_convrot_group_size;
+ }
+
+ bool same_source(const TensorStorage& a, const TensorStorage& b) {
+ return a.file_id == b.file_id && a.file_revision == b.file_revision && a.file_index == b.file_index && same_encoding(a, b);
+ }
+
+ bool same_sources(const std::vector<TensorStorage>& a, const std::vector<TensorStorage>& b) {
+ return std::equal(a.begin(), a.end(), b.begin(), b.end(), same_source);
+ }
+
+ bool same_weight(const ModelLoader& a_loader,
+ const std::vector<TensorStorage>& a,
+ const ModelLoader& b_loader,
+ const std::vector<TensorStorage>& b) {
+ return std::equal(a.begin(), a.end(), b.begin(), b.end(), [&](const TensorStorage& x, const TensorStorage& y) {
+ return same_encoding(x, y) && a_loader.same_weight_file(x.file_id, x.file_index, b_loader, y.file_id, y.file_index);
+ });
+ }
+}
diff --git a/src/weights/sources.h b/src/weights/sources.h
new file mode 100644
index 0000000..5bcd0bc
--- /dev/null
+++ b/src/weights/sources.h
@@ -0,0 +1,32 @@
+#ifndef __SD_WEIGHTS_SOURCES_H__
+#define __SD_WEIGHTS_SOURCES_H__
+
+#include <string>
+#include <vector>
+
+#include "model_loader.h"
+
+namespace sd::weights {
+ // Rules for where a weight's data comes from. They decide which weights share a copy and which
+ // copies a file change invalidates; buffers and bindings stay with the residency store.
+
+ // The parts of a weight in its files: the tensor itself, or ".1", ".2", ... when the registered
+ // shape is larger than the first part. Adapter weights are always a single tensor.
+ std::vector<TensorStorage> find_sources(const std::string& name,
+ const int64_t* registered_ne,
+ bool single_tensor,
+ const String2TensorStorage& sources);
+
+ // Same bytes in the file and the same decoding.
+ bool same_encoding(const TensorStorage& a, const TensorStorage& b);
+ // Same file revision, position and encoding: a copy of one serves the other.
+ bool same_source(const TensorStorage& a, const TensorStorage& b);
+ bool same_sources(const std::vector<TensorStorage>& a, const std::vector<TensorStorage>& b);
+ // Two weights read the same data, possibly through different loaders of the same file.
+ bool same_weight(const ModelLoader& a_loader,
+ const std::vector<TensorStorage>& a,
+ const ModelLoader& b_loader,
+ const std::vector<TensorStorage>& b);
+}
+
+#endif // __SD_WEIGHTS_SOURCES_H__
diff --git a/src/weights/state.h b/src/weights/state.h
new file mode 100644
index 0000000..6a6d4a4
--- /dev/null
+++ b/src/weights/state.h
@@ -0,0 +1,66 @@
+#ifndef __SD_WEIGHTS_STATE_H__
+#define __SD_WEIGHTS_STATE_H__
+
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+namespace sd::weights {
+ // Read-only view of weight allocations. A weight can have several copies: an original in
+ // its params location or lower, and compute or merged copies. The model file is the implicit
+ // lowest location of every file-backed weight.
+ enum class Tier {
+ Device,
+ Host,
+ };
+
+ enum class AllocationKind {
+ // Compute copy staged from a lower location or the model file.
+ Compute,
+ // Params storage: the original, or a merge applied to it in place.
+ Storage,
+ // RAM copy of merged LoRA weights.
+ MergedCache,
+ };
+
+ using WeightId = uintptr_t;
+ using ResourceId = uintptr_t;
+
+ struct Copy {
+ WeightId weight = 0;
+ ResourceId resource = 0;
+ size_t next_use = 0;
+ uint64_t last_use = 0;
+ // In use by a graph, or a merge reads it.
+ bool leased = false;
+ // Reserved by an asynchronous upload.
+ bool prefetched = false;
+ // The model file can reproduce it; split, view and custom-operator weights cannot move.
+ bool movable = true;
+ // Another copy serves the weight now, e.g. an original whose merged copy is separate.
+ // Leases and protection of the weight do not keep this copy.
+ bool superseded = false;
+ // A lower residency location exists for it, so leaving needs a copy.
+ bool has_lower_location = false;
+ // Device bytes to allocate if a required weight has to load again after it leaves.
+ size_t reload_bytes = 0;
+ // Shared weights of several components.
+ bool shared = false;
+ };
+
+ struct Allocation {
+ uintptr_t id = 0;
+ Tier tier = Tier::Device;
+ AllocationKind kind;
+ size_t bytes = 0;
+ // Loader-retained mappings cannot be reclaimed by freeing them.
+ bool fixed = false;
+ std::vector<Copy> copies;
+ };
+
+ struct Snapshot {
+ std::vector<Allocation> allocations;
+ };
+}
+
+#endif // __SD_WEIGHTS_STATE_H__
diff --git a/src/weights/store.cpp b/src/weights/store.cpp
new file mode 100644
index 0000000..d81ac37
--- /dev/null
+++ b/src/weights/store.cpp
@@ -0,0 +1,386 @@
+#include "weights/store.h"
+
+#include <algorithm>
+
+#include <unordered_map>
+
+#include "core/ggml_extend_backend.h"
+#include "core/util.h"
+
+namespace sd::weights {
+
+ // Every change to a copy binding, block membership, lease, merged version or file source is made
+ // here, so bindings and block membership stay consistent.
+
+ TensorState* WeightStore::add_state(std::unique_ptr<TensorState> state) {
+ auto* added = state.get();
+ tensor_states_by_tensor_[added->tensor] = added;
+ tensor_states_.push_back(std::move(state));
+ return added;
+ }
+
+ void WeightStore::remove_states(const std::unordered_set<TensorState*>& states) {
+ for (auto it = tensor_states_by_tensor_.begin(); it != tensor_states_by_tensor_.end();) {
+ if (states.count(it->second) != 0)
+ it = tensor_states_by_tensor_.erase(it);
+ else
+ ++it;
+ }
+ tensor_states_.erase(std::remove_if(tensor_states_.begin(), tensor_states_.end(),
+ [&](const auto& state) { return states.count(state.get()) != 0; }),
+ tensor_states_.end());
+ }
+
+ ParamsStorageBlock* WeightStore::add_storage(std::unique_ptr<ParamsStorageBlock> block) {
+ auto* added = block.get();
+ params_storage_blocks_.push_back(std::move(block));
+ return added;
+ }
+
+ void WeightStore::bind_loaded(const std::vector<TensorState*>& states) {
+ std::unordered_map<const TensorState*, ParamsStorageBlock*> blocks;
+ for (const auto& block : params_storage_blocks_) {
+ for (auto* state : block->states)
+ blocks.emplace(state, block.get());
+ }
+ for (auto* state : states) {
+ if (state == nullptr)
+ continue;
+ const auto found = blocks.find(state);
+ state->bind_storage(found != blocks.end() && !state->tensor->view_src ? found->second : &view_storage_);
+ }
+ check_residency();
+ }
+
+ void WeightStore::share(TensorState& state, ParamsStorageBlock& block, const ggml_tensor& data, ggml_backend_t location) {
+ block.states.push_back(&state);
+ block.shared = true;
+ state.tensor->buffer = data.buffer;
+ state.tensor->data = data.data;
+ state.tensor->extra = data.extra;
+ state.bind_storage(&block);
+ state.read_from_file(false);
+ state.move_to(location);
+ }
+
+ void WeightStore::replace_storage_buffer(ParamsStorageBlock& block, ggml_backend_buffer_t buffer, ggml_backend_t location) {
+ for (auto* state : block.states)
+ state->move_to(location);
+ ggml_backend_buffer_free(block.buffer);
+ block.buffer = buffer;
+ }
+
+ void WeightStore::release_storage(ParamsStorageBlock* block, bool use_model_file) {
+ free_params_storage_block(*block, use_model_file);
+ erase_params_storage_block(block);
+ }
+
+ ComputeStagingBlock* WeightStore::add_compute(std::unique_ptr<ComputeStagingBlock> block,
+ const std::vector<uint64_t>& epochs) {
+ auto* added = block.get();
+ for (size_t i = 0; i < added->staged_tensors.size(); ++i)
+ added->staged_tensors[i].first->bind_compute(added, epochs[i]);
+ compute_staging_blocks_.push_back(std::move(block));
+ return added;
+ }
+
+ ggml_backend_buffer_t WeightStore::release_compute(ComputeStagingBlock* block, bool keep_buffer) {
+ ggml_backend_buffer_t kept = nullptr;
+ if (keep_buffer) {
+ kept = block->buffer;
+ block->buffer = nullptr;
+ }
+ free_compute_staging_block(*block);
+ compute_staging_blocks_.erase(std::find_if(compute_staging_blocks_.begin(), compute_staging_blocks_.end(),
+ [&](const auto& item) { return item.get() == block; }));
+ return kept;
+ }
+
+ void WeightStore::release_all() {
+ for (auto& state : tensor_states_) {
+ state->clear_leases();
+ state->reset_merges();
+ }
+ release_compute_staging_blocks(true);
+ release_params_storage_blocks(true);
+ }
+
+ void WeightStore::free_compute_staging_block(ComputeStagingBlock& block) {
+ for (auto& staged_tensor : block.staged_tensors) {
+ TensorState* state = staged_tensor.first;
+ ggml_tensor* staging_tensor = staged_tensor.second;
+ if (state == nullptr || state->tensor == nullptr || staging_tensor == nullptr) {
+ continue;
+ }
+ ggml_tensor* managed_tensor = state->tensor;
+ managed_tensor->buffer = staging_tensor->buffer;
+ managed_tensor->data = staging_tensor->data;
+ managed_tensor->extra = staging_tensor->extra;
+ staging_tensor->buffer = nullptr;
+ staging_tensor->data = nullptr;
+ staging_tensor->extra = nullptr;
+
+ state->unbind_compute();
+ if (!state->loaded()) {
+ if (!separate_merge_(*state)) {
+ state->read_from_file(false);
+ }
+ reset_location(*state);
+ }
+ }
+
+ if (block.buffer != nullptr) {
+ ggml_backend_buffer_free(block.buffer);
+ block.buffer = nullptr;
+ }
+ if (block.staging_ctx != nullptr) {
+ ggml_free(block.staging_ctx);
+ block.staging_ctx = nullptr;
+ }
+ block.staged_tensors.clear();
+ }
+
+ void WeightStore::release_compute_staging_blocks(bool force,
+ const std::unordered_set<TensorState*>* target_states) {
+ struct ReleaseStats {
+ size_t bytes = 0;
+ size_t tensors = 0;
+ size_t blocks = 0;
+ };
+ std::map<ggml_backend_t, ReleaseStats> released;
+ for (auto it = compute_staging_blocks_.begin(); it != compute_staging_blocks_.end();) {
+ ComputeStagingBlock* block = it->get();
+ bool can_release = force;
+ if (!can_release) {
+ can_release = std::all_of(block->staged_tensors.begin(),
+ block->staged_tensors.end(),
+ [target_states](const std::pair<TensorState*, ggml_tensor*>& pair) {
+ TensorState* state = pair.first;
+ if (state == nullptr) {
+ return true;
+ }
+ if (target_states != nullptr &&
+ target_states->find(state) == target_states->end()) {
+ return false;
+ }
+ return state->pin_count() == 0;
+ });
+ }
+
+ if (can_release) {
+ if (block->buffer != nullptr) {
+ auto& stats = released[block->compute_backend];
+ stats.bytes += ggml_backend_buffer_get_size(block->buffer);
+ stats.tensors += block->staged_tensors.size();
+ ++stats.blocks;
+ }
+ free_compute_staging_block(*block);
+ it = compute_staging_blocks_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ for (const auto& entry : released) {
+ LOG_DEBUG("model manager released compute params (%6.2f MB, %zu tensors, %zu blocks) from %s",
+ entry.second.bytes / (1024.f * 1024.f),
+ entry.second.tensors, entry.second.blocks,
+ entry.first != nullptr ? ggml_backend_name(entry.first) : "unknown");
+ }
+ }
+
+ void WeightStore::free_params_storage_block(ParamsStorageBlock& block, bool use_model_file) {
+ use_model_file = use_model_file || below_home(block);
+ if (use_model_file) {
+ // The active compute copy can outlive its host source. Clear the saved binding
+ // so eviction of that copy leaves the tensor unloaded.
+ for (const auto& staging : compute_staging_blocks_) {
+ for (const auto& [_, original] : staging->staged_tensors) {
+ if (original && original->buffer == block.buffer) {
+ original->buffer = nullptr;
+ original->data = nullptr;
+ original->extra = nullptr;
+ }
+ }
+ }
+ }
+ if (block.buffer != nullptr) {
+ LOG_DEBUG("free params buffer: %.2f MB(%s), %zu tensors on %s",
+ ggml_backend_buffer_get_size(block.buffer) / (1024.0 * 1024.0),
+ ggml_backend_buffer_is_host(block.buffer) ? "RAM" : "VRAM",
+ block.states.size(), ggml_backend_buffer_name(block.buffer));
+ ggml_backend_buffer_free(block.buffer);
+ block.buffer = nullptr;
+ }
+ block.mmap_tensor_stores.clear();
+
+ for (TensorState* state : block.states) {
+ if (state == nullptr || state->tensor == nullptr) {
+ continue;
+ }
+ state->unbind_storage();
+ // Shared LoRA sources stay out of device memory; their compute copies read the model file.
+ const bool file_source = use_model_file && (state->staged() || separate_merge_(*state));
+ state->read_from_file(file_source);
+ if (use_model_file && state->staged()) {
+ continue;
+ }
+ state->tensor->buffer = nullptr;
+ state->tensor->data = nullptr;
+ state->tensor->extra = nullptr;
+
+ state->reset_merges();
+ reset_location(*state);
+ }
+ block.states.clear();
+ }
+
+ void WeightStore::release_params_storage_blocks(bool force,
+ const std::unordered_set<TensorState*>* target_states) {
+ for (auto it = params_storage_blocks_.begin(); it != params_storage_blocks_.end();) {
+ ParamsStorageBlock* block = it->get();
+ bool can_release = force;
+ if (!can_release) {
+ can_release = std::all_of(block->states.begin(),
+ block->states.end(),
+ [target_states](TensorState* state) {
+ if (state == nullptr) {
+ return true;
+ }
+ if (target_states != nullptr &&
+ target_states->find(state) == target_states->end()) {
+ return false;
+ }
+ return state->pin_count() == 0 &&
+ !state->staged();
+ });
+ }
+
+ if (can_release) {
+ free_params_storage_block(*block);
+ it = params_storage_blocks_.erase(it);
+ } else {
+ ++it;
+ }
+ }
+ }
+
+ void WeightStore::erase_params_storage_block(ParamsStorageBlock* block) {
+ auto it = std::find_if(params_storage_blocks_.begin(),
+ params_storage_blocks_.end(),
+ [block](const std::unique_ptr<ParamsStorageBlock>& item) {
+ return item.get() == block;
+ });
+ if (it != params_storage_blocks_.end()) {
+ params_storage_blocks_.erase(it);
+ }
+ }
+
+ ParamsStorageBlock* WeightStore::storage_block_for(const TensorState& state) {
+ // A view's data lives in its base weight's allocation.
+ if (state.tensor && state.tensor->view_src)
+ return &view_storage_;
+ for (const auto& block : params_storage_blocks_) {
+ if (std::find(block->states.begin(), block->states.end(), &state) != block->states.end())
+ return block.get();
+ }
+ return &view_storage_;
+ }
+
+ void WeightStore::check_residency() const {
+#ifndef NDEBUG
+ for (const auto& block : params_storage_blocks_) {
+ for (auto* state : block->states)
+ GGML_ASSERT(!state->loaded() || state->storage_copy() == block.get() || state->storage_copy() == &view_storage_);
+ }
+ for (const auto& block : compute_staging_blocks_) {
+ for (const auto& entry : block->staged_tensors)
+ GGML_ASSERT(!entry.first || entry.first->compute_copy() == block.get());
+ }
+ for (const auto& state : tensor_states_) {
+ if (state->loaded() && state->storage_copy() != &view_storage_) {
+ const auto* copy = state->storage_copy();
+ GGML_ASSERT(std::any_of(params_storage_blocks_.begin(), params_storage_blocks_.end(), [&](const auto& block) {
+ return block.get() == copy && std::find(block->states.begin(), block->states.end(), state.get()) != block->states.end();
+ }));
+ }
+ if (state->staged()) {
+ const auto* copy = state->compute_copy();
+ GGML_ASSERT(std::any_of(compute_staging_blocks_.begin(), compute_staging_blocks_.end(),
+ [&](const auto& block) { return block.get() == copy; }));
+ }
+ }
+#endif
+ }
+
+ bool WeightStore::discard_lora_staging(const std::unordered_set<TensorState*>& states) {
+ auto release = states;
+ for (const auto& block : compute_staging_blocks_) {
+ if (std::none_of(block->staged_tensors.begin(), block->staged_tensors.end(),
+ [&](const auto& entry) { return states.count(entry.first) != 0; })) {
+ continue;
+ }
+ for (const auto& [state, _] : block->staged_tensors) {
+ if (state->pin_count() != 0) {
+ return false;
+ }
+ release.insert(state);
+ }
+ }
+ release_compute_staging_blocks(false, &release);
+ return true;
+ }
+
+ void WeightStore::detach_shared_weight(TensorState& state) {
+ // Only an idle copy shared with siblings detaches; the caller decides the weight shares at all.
+ if (!state.loaded() || state.staged() || state.pin_count() != 0)
+ return;
+ for (auto& block : params_storage_blocks_) {
+ if (!block->shared || block->states.size() < 2)
+ continue;
+ auto found = std::find(block->states.begin(), block->states.end(), &state);
+ if (found == block->states.end())
+ continue;
+ block->states.erase(found);
+ state.tensor->buffer = nullptr;
+ state.tensor->data = nullptr;
+ state.tensor->extra = nullptr;
+ state.unbind_storage();
+ state.read_from_file(false);
+ state.reset_merges();
+ reset_location(state);
+ return;
+ }
+ }
+
+ void WeightStore::leave_shared_blocks(const std::unordered_set<TensorState*>& states) {
+ for (auto& block : params_storage_blocks_) {
+ if (!block->shared)
+ continue;
+ auto& members = block->states;
+ members.erase(std::remove_if(members.begin(), members.end(),
+ [&](TensorState* state) {
+ if (states.count(state) == 0)
+ return false;
+ if (state->storage_copy() == block.get())
+ state->unbind_storage();
+ return true;
+ }),
+ members.end());
+ }
+ }
+
+ ggml_backend_t home_backend(const TensorState& state) {
+ return state.residency_mode == ResidencyMode::Disk || !state.preferred_backend ? state.compute_backend : state.preferred_backend;
+ }
+
+ bool below_home(const ParamsStorageBlock& block) {
+ if (!block.buffer || block.states.empty())
+ return false;
+ const auto home = home_backend(*block.states.front());
+ if (!home)
+ return false;
+ if (ggml_backend_buffer_is_host(block.buffer))
+ return !sd_backend_is_cpu(home);
+ return ggml_backend_buft_get_device(ggml_backend_buffer_get_type(block.buffer)) != ggml_backend_get_device(home);
+ }
+} // namespace sd::weights
diff --git a/src/weights/store.h b/src/weights/store.h
new file mode 100644
index 0000000..c2c7192
--- /dev/null
+++ b/src/weights/store.h
@@ -0,0 +1,216 @@
+#ifndef __SD_WEIGHTS_STORE_H__
+#define __SD_WEIGHTS_STORE_H__
+
+#include <cstdint>
+#include <map>
+#include <memory>
+#include <string>
+#include <unordered_set>
+#include <vector>
+
+#include "ggml-backend.h"
+#include "model_component.h"
+#include "model_loader.h"
+
+namespace sd::weights {
+ enum class ResidencyMode {
+ Disk,
+ ParamBackend,
+ };
+
+ enum class ParamSource {
+ Backend,
+ // The compute copy is read from the model file instead of a params copy.
+ ModelFile,
+ };
+
+ struct CachedLoraWeight {
+ ggml_tensor tensor;
+ ggml_backend_t compute_backend;
+ uint64_t lora_epoch;
+ };
+
+ struct ParamsStorageBlock;
+ struct ComputeStagingBlock;
+ class WeightStore;
+ struct TensorState;
+
+ // Disk residency keeps no copy above the model file, so its weights load on the compute device.
+ ggml_backend_t home_backend(const TensorState& state);
+ // The block holds copies below their params location, e.g. after leaving the device.
+ bool below_home(const ParamsStorageBlock& block);
+
+ struct TensorState {
+ // Opaque identifier of the owning resource; the store never dereferences it.
+ void* resource = nullptr;
+ std::string name;
+ ggml_tensor* tensor = nullptr;
+ ModelComponent component = ModelComponent::Count;
+ std::vector<TensorStorage> sources;
+ ModelLoader::FileId source_file = 0;
+ SDVersion source_version = VERSION_COUNT;
+
+ // Configured residency preference. Automatic residency only reads it.
+ ResidencyMode residency_mode = ResidencyMode::ParamBackend;
+ ggml_backend_t preferred_backend = nullptr;
+
+ ggml_backend_t compute_backend = nullptr;
+ ggml_backend_buffer_type_t split_buffer_type = nullptr;
+ bool params_follow_compute_backend = false;
+ bool metadata_validated = false;
+ enum ggml_op usage_op = GGML_OP_NONE;
+ TensorState* lora_int8_partner = nullptr;
+ bool is_int8_weight = false;
+ uint64_t last_use_epoch = 0;
+
+ private:
+ // Residency is this weight's copies. Only the transitions below change it.
+ ParamsStorageBlock* storage_copy_ = nullptr;
+ ComputeStagingBlock* compute_copy_ = nullptr;
+ uint64_t storage_epoch_ = UINT64_MAX;
+ uint64_t compute_epoch_ = UINT64_MAX;
+ ParamSource param_source_ = ParamSource::Backend;
+ ggml_backend_t params_backend_ = nullptr;
+ int pin_count_ = 0;
+ std::shared_ptr<const CachedLoraWeight> cached_lora_;
+
+ public:
+ bool loaded() const { return storage_copy_ != nullptr; }
+ bool staged() const { return compute_copy_ != nullptr; }
+ const ParamsStorageBlock* storage_copy() const { return storage_copy_; }
+ const ComputeStagingBlock* compute_copy() const { return compute_copy_; }
+ // LoRA epoch of the copy the graph reads; UINT64_MAX means no merge.
+ uint64_t applied_epoch() const { return compute_copy_ ? compute_epoch_ : storage_epoch_; }
+ uint64_t storage_epoch() const { return storage_epoch_; }
+ ParamSource param_source() const { return param_source_; }
+ // Location of the params copy, or where the next load goes while there is none.
+ ggml_backend_t params_backend() const { return params_backend_; }
+ int pin_count() const { return pin_count_; }
+ const std::shared_ptr<const CachedLoraWeight>& cached_lora() const { return cached_lora_; }
+
+ private:
+ // Only the store changes residency, so bindings and block membership stay consistent.
+ friend class WeightStore;
+ // The storage copy holds the original, or a merge applied to it in place.
+ void bind_storage(ParamsStorageBlock* block) { storage_copy_ = block; }
+ void unbind_storage() {
+ storage_copy_ = nullptr;
+ storage_epoch_ = UINT64_MAX;
+ }
+ // A compute copy starts as a copy of its source, with that source's merge.
+ void bind_compute(ComputeStagingBlock* block, uint64_t epoch) {
+ compute_copy_ = block;
+ compute_epoch_ = epoch;
+ }
+ void unbind_compute() {
+ compute_copy_ = nullptr;
+ compute_epoch_ = UINT64_MAX;
+ }
+ // Records a merge into the copy the graph reads.
+ void mark_merged(uint64_t epoch) { (compute_copy_ ? compute_epoch_ : storage_epoch_) = epoch; }
+ void reset_merges() { storage_epoch_ = compute_epoch_ = UINT64_MAX; }
+ void read_from_file(bool file) { param_source_ = file ? ParamSource::ModelFile : ParamSource::Backend; }
+ void move_to(ggml_backend_t backend) { params_backend_ = backend; }
+ void lease() { ++pin_count_; }
+ void release_lease() {
+ if (pin_count_ > 0)
+ --pin_count_;
+ }
+ void clear_leases() { pin_count_ = 0; }
+ void cache_merged(std::shared_ptr<const CachedLoraWeight> cached) { cached_lora_ = std::move(cached); }
+ void drop_merged_cache() { cached_lora_.reset(); }
+ };
+
+ struct ParamsStorageBlock {
+ ggml_backend_buffer_t buffer = nullptr;
+ std::vector<MmapTensorStore> mmap_tensor_stores;
+ std::vector<TensorState*> states;
+ bool shared = false;
+ };
+
+ struct ComputeStagingBlock {
+ ggml_backend_t compute_backend = nullptr;
+ ggml_backend_buffer_t buffer = nullptr;
+ ggml_context* staging_ctx = nullptr;
+ std::vector<std::pair<TensorState*, ggml_tensor*>> staged_tensors;
+ };
+
+ // Owns the weights' index and copies. Every change to a copy binding, block membership, lease,
+ // merged version or file source goes through it.
+ class WeightStore {
+ public:
+ // Whether a weight's merged LoRA version lives in a separate compute copy. It depends on the
+ // resource's LoRA configuration, which only the owner knows.
+ using SeparateMerge = bool (*)(const TensorState& state);
+ explicit WeightStore(SeparateMerge separate_merge)
+ : separate_merge_(separate_merge) {}
+
+ const std::vector<std::unique_ptr<TensorState>>& tensor_states() const { return tensor_states_; }
+ const std::map<const ggml_tensor*, TensorState*>& tensor_index() const { return tensor_states_by_tensor_; }
+ const std::vector<std::unique_ptr<ParamsStorageBlock>>& storage_blocks() const { return params_storage_blocks_; }
+ const std::vector<std::unique_ptr<ComputeStagingBlock>>& compute_blocks() const { return compute_staging_blocks_; }
+ // Marker storage of weights whose data lives in another allocation, such as views.
+ const ParamsStorageBlock* view_storage() const { return &view_storage_; }
+
+ TensorState* add_state(std::unique_ptr<TensorState> state);
+ void remove_states(const std::unordered_set<TensorState*>& states);
+
+ // A block joins residency when added; its weights bind once their data is loaded.
+ ParamsStorageBlock* add_storage(std::unique_ptr<ParamsStorageBlock> block);
+ void bind_loaded(const std::vector<TensorState*>& states);
+ // Binds a sibling to an existing copy of the same weight.
+ void share(TensorState& state, ParamsStorageBlock& block, const ggml_tensor& data, ggml_backend_t location);
+ void detach_shared_weight(TensorState& state);
+ // Unregistration: the weights leave shared blocks, whose storage stays for the other members.
+ void leave_shared_blocks(const std::unordered_set<TensorState*>& states);
+ // A demoted copy: the block now holds the weights at location.
+ void replace_storage_buffer(ParamsStorageBlock& block, ggml_backend_buffer_t buffer, ggml_backend_t location);
+ void free_params_storage_block(ParamsStorageBlock& block, bool use_model_file = false);
+ void erase_params_storage_block(ParamsStorageBlock* block);
+ void release_storage(ParamsStorageBlock* block, bool use_model_file);
+ void release_params_storage_blocks(bool force = false,
+ const std::unordered_set<TensorState*>* target_states = nullptr);
+
+ // Binds each staged weight to the block with the merged version its copy holds.
+ ComputeStagingBlock* add_compute(std::unique_ptr<ComputeStagingBlock> block, const std::vector<uint64_t>& epochs);
+ void free_compute_staging_block(ComputeStagingBlock& block);
+ // Frees and removes the block; keep_buffer hands its allocation to the caller instead.
+ ggml_backend_buffer_t release_compute(ComputeStagingBlock* block, bool keep_buffer = false);
+ void release_compute_staging_blocks(bool force = false,
+ const std::unordered_set<TensorState*>* target_states = nullptr);
+ bool discard_lora_staging(const std::unordered_set<TensorState*>& states);
+ void release_all();
+
+ ParamsStorageBlock* storage_block_for(const TensorState& state);
+ void check_residency() const;
+
+ static void reset_location(TensorState& state) { state.move_to(home_backend(state)); }
+ static void move_to(TensorState& state, ggml_backend_t backend) { state.move_to(backend); }
+ static void read_from_file(TensorState& state, bool file) { state.read_from_file(file); }
+ static void mark_merged(TensorState& state, uint64_t epoch) { state.mark_merged(epoch); }
+ static void reset_merges(TensorState& state) { state.reset_merges(); }
+ static void cache_merged(TensorState& state, std::shared_ptr<const CachedLoraWeight> cached) { state.cache_merged(std::move(cached)); }
+ static void drop_merged_cache(TensorState& state) { state.drop_merged_cache(); }
+ static void lease(TensorState& state) { state.lease(); }
+ static void release_lease(TensorState& state) { state.release_lease(); }
+ // Unregistration keeps the tensor; its data and every copy are gone.
+ static void forget(TensorState& state) {
+ state.unbind_storage();
+ state.read_from_file(false);
+ state.reset_merges();
+ state.drop_merged_cache();
+ reset_location(state);
+ }
+
+ private:
+ SeparateMerge separate_merge_;
+ std::vector<std::unique_ptr<TensorState>> tensor_states_;
+ std::map<const ggml_tensor*, TensorState*> tensor_states_by_tensor_;
+ std::vector<std::unique_ptr<ParamsStorageBlock>> params_storage_blocks_;
+ ParamsStorageBlock view_storage_;
+ std::vector<std::unique_ptr<ComputeStagingBlock>> compute_staging_blocks_;
+ };
+
+}
+
+#endif // __SD_WEIGHTS_STORE_H__
diff --git a/src/weights/weight_copy.cpp b/src/weights/weight_copy.cpp
new file mode 100644
index 0000000..1e3d533
--- /dev/null
+++ b/src/weights/weight_copy.cpp
@@ -0,0 +1,44 @@
+#include "weights/weight_copy.h"
+
+#include <algorithm>
+
+#include "ggml.h"
+
+namespace sd::weights {
+ size_t weight_copy_bytes(ggml_backend_buffer_type_t buft, const WeightCopies& copies) {
+ const auto alignment = ggml_backend_buft_get_alignment(buft);
+ size_t bytes = 0;
+ for (const auto& copy : copies) {
+ const auto size = GGML_PAD(ggml_backend_buft_get_alloc_size(buft, copy.first), alignment);
+ bytes += std::min(size, SIZE_MAX - bytes);
+ }
+ return bytes;
+ }
+
+ BackendBuffer copy_weights(ggml_backend_buffer_type_t buft, ggml_backend_t backend, const WeightCopies& copies, size_t bytes) {
+ const auto alignment = ggml_backend_buft_get_alignment(buft);
+ BackendBuffer target(ggml_backend_buft_alloc_buffer(buft, bytes), ggml_backend_buffer_free);
+ if (!target) {
+ return target;
+ }
+ ggml_backend_buffer_set_usage(target.get(), GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
+ auto* base = static_cast<char*>(ggml_backend_buffer_get_base(target.get()));
+ size_t offset = 0;
+ for (const auto& [source, destination] : copies) {
+ *destination = *source;
+ destination->buffer = nullptr;
+ destination->data = nullptr;
+ destination->extra = nullptr;
+ if (ggml_backend_tensor_alloc(target.get(), destination, base + offset) != GGML_STATUS_SUCCESS) {
+ target.reset();
+ return target;
+ }
+ offset += GGML_PAD(ggml_backend_buft_get_alloc_size(buft, destination), alignment);
+ }
+ ggml_backend_synchronize(backend);
+ for (const auto& [source, destination] : copies) {
+ ggml_backend_tensor_copy(source, destination);
+ }
+ return target;
+ }
+}
diff --git a/src/weights/weight_copy.h b/src/weights/weight_copy.h
new file mode 100644
index 0000000..ea7085b
--- /dev/null
+++ b/src/weights/weight_copy.h
@@ -0,0 +1,21 @@
+#ifndef __SD_WEIGHTS_WEIGHT_COPY_H__
+#define __SD_WEIGHTS_WEIGHT_COPY_H__
+
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "ggml-backend.h"
+
+namespace sd::weights {
+ using BackendBuffer = std::unique_ptr<ggml_backend_buffer, decltype(&ggml_backend_buffer_free)>;
+ // Source tensor and the tensor that receives its copy.
+ using WeightCopies = std::vector<std::pair<ggml_tensor*, ggml_tensor*>>;
+
+ // Bytes one buffer of buft needs to hold the copies.
+ size_t weight_copy_bytes(ggml_backend_buffer_type_t buft, const WeightCopies& copies);
+ // Allocates one buffer of buft and copies each source into its destination tensor there.
+ BackendBuffer copy_weights(ggml_backend_buffer_type_t buft, ggml_backend_t backend, const WeightCopies& copies, size_t bytes);
+}
+
+#endif // __SD_WEIGHTS_WEIGHT_COPY_H__
diff --git a/src/weights/weight_reader.cpp b/src/weights/weight_reader.cpp
new file mode 100644
index 0000000..7fd581f
--- /dev/null
+++ b/src/weights/weight_reader.cpp
@@ -0,0 +1,143 @@
+#include "weights/weight_reader.h"
+
+#include <algorithm>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <set>
+#include <tuple>
+
+namespace sd::weights {
+ namespace {
+ using ReadGroup = std::tuple<ModelLoader*, ModelLoader::FileId, SDVersion, bool>;
+ using ReadBatch = std::map<std::string, std::vector<ggml_tensor*>>;
+
+ bool read_batch(const ReadGroup& group, ReadBatch& batch, bool log_progress) {
+ std::set<std::string> names, loaded;
+ std::mutex mutex;
+ for (const auto& entry : batch)
+ names.insert(entry.first);
+ auto callback = [&](const TensorStorage& source, ggml_tensor** dst) {
+ *dst = nullptr;
+ auto found = batch.find(source.name);
+ if (found == batch.end())
+ return true;
+ *dst = found->second.front();
+ std::lock_guard<std::mutex> lock(mutex);
+ loaded.insert(source.name);
+ return true;
+ };
+ const auto [loader, file, version, use_mmap] = group;
+ const bool success = file == 0 ? loader->load_tensors(callback, use_mmap, &names, log_progress)
+ : loader->load_file_tensors(file, version, callback, names, use_mmap);
+ if (!success || loaded != names)
+ return false;
+ for (auto& entry : batch) {
+ auto* first = entry.second.front();
+ for (auto* tensor : entry.second) {
+ if (tensor != first)
+ ggml_backend_tensor_copy(first, tensor);
+ }
+ }
+ return true;
+ }
+
+ // Assembles a device tensor from its parts in RAM and uploads it once, including for
+ // row-split buffers.
+ bool read_device_parts(const ReadTarget& target) {
+ const auto& sources = *target.sources;
+ auto ctx = std::unique_ptr<ggml_context, decltype(&ggml_free)>(
+ ggml_init({sources.size() * ggml_tensor_overhead(), nullptr, true}), ggml_free);
+ if (!ctx)
+ return false;
+ const size_t size = ggml_nbytes(target.destination);
+ std::vector<uint8_t> buffer(size);
+ ReadBatch batch;
+ size_t offset = 0;
+ for (const auto& source : sources) {
+ auto* part = ggml_new_tensor(ctx.get(), target.destination->type, source.n_dims, source.ne);
+ const size_t part_size = ggml_nbytes(part);
+ if (part_size > size - offset)
+ return false;
+ part->data = buffer.data() + offset;
+ batch[source.name].push_back(part);
+ offset += part_size;
+ }
+ if (offset != size)
+ return false;
+ if (!read_batch({target.loader, target.file, target.version, target.use_mmap}, batch, false))
+ return false;
+ ggml_backend_tensor_set(target.destination, buffer.data(), 0, size);
+ return true;
+ }
+ }
+
+ bool read_weights(const std::vector<ReadTarget>& targets) {
+ std::map<ReadGroup, std::vector<ReadBatch>> groups;
+ size_t part_count = 0;
+ for (const auto& target : targets) {
+ if (!target.loader || !target.destination)
+ return false;
+ if (target.sources && target.sources->size() > 1 && ggml_backend_buffer_is_host(target.destination->buffer))
+ part_count += target.sources->size();
+ }
+ auto parts_ctx = std::unique_ptr<ggml_context, decltype(&ggml_free)>(
+ part_count > 0 ? ggml_init({part_count * ggml_tensor_overhead(), nullptr, true}) : nullptr, ggml_free);
+ if (part_count > 0 && !parts_ctx)
+ return false;
+ auto add_destination = [&](const ReadTarget& target, const std::string& name, ggml_tensor* tensor) {
+ auto& batches = groups[{target.loader, target.file, target.version, target.use_mmap}];
+ // The loader supplies one destination per name; incompatible destinations need another batch.
+ auto batch = std::find_if(batches.begin(), batches.end(), [&](const ReadBatch& candidate) {
+ auto found = candidate.find(name);
+ return found == candidate.end() ||
+ (found->second.front()->type == tensor->type && ggml_are_same_shape(found->second.front(), tensor));
+ });
+ if (batch == batches.end()) {
+ batches.emplace_back();
+ batch = std::prev(batches.end());
+ }
+ (*batch)[name].push_back(tensor);
+ };
+ for (const auto& target : targets) {
+ if (!target.sources || target.sources->size() <= 1) {
+ add_destination(target, target.name, target.destination);
+ continue;
+ }
+ if (!ggml_backend_buffer_is_host(target.destination->buffer)) {
+ if (!read_device_parts(target))
+ return false;
+ continue;
+ }
+ // Host parts are read straight into their slices of the destination.
+ const size_t size = ggml_nbytes(target.destination);
+ size_t offset = 0;
+ for (const auto& source : *target.sources) {
+ auto* part = ggml_new_tensor(parts_ctx.get(), target.destination->type, source.n_dims, source.ne);
+ const size_t part_size = ggml_nbytes(part);
+ if (part_size > size - offset)
+ return false;
+ part->data = static_cast<uint8_t*>(target.destination->data) + offset;
+ part->buffer = target.destination->buffer;
+ add_destination(target, source.name, part);
+ offset += part_size;
+ }
+ if (offset != size)
+ return false;
+ }
+ for (auto& [group, batches] : groups) {
+ for (auto& batch : batches) {
+ if (!read_batch(group, batch, true))
+ return false;
+ }
+ }
+ return true;
+ }
+
+ std::vector<MmapTensorStore> map_weights(ModelLoader& loader,
+ std::map<std::string, ggml_tensor*>& tensors,
+ bool writable,
+ ggml_backend_dev_t device) {
+ return loader.mmap_tensors(tensors, {}, writable, device);
+ }
+}
diff --git a/src/weights/weight_reader.h b/src/weights/weight_reader.h
new file mode 100644
index 0000000..6551849
--- /dev/null
+++ b/src/weights/weight_reader.h
@@ -0,0 +1,37 @@
+#ifndef __SD_WEIGHTS_WEIGHT_READER_H__
+#define __SD_WEIGHTS_WEIGHT_READER_H__
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "model_loader.h"
+
+namespace sd::weights {
+ // One weight to read into a destination tensor. The caller owns the destination
+ // allocation and decides where it lives; the reader only delivers data.
+ struct ReadTarget {
+ ModelLoader* loader = nullptr;
+ // 0 reads the loader's main files; other ids read an auxiliary file.
+ ModelLoader::FileId file = 0;
+ SDVersion version = VERSION_COUNT;
+ bool use_mmap = false;
+ // Name of a single-source weight in the file.
+ std::string name;
+ // Parts concatenated in order when the weight has several sources.
+ const std::vector<TensorStorage>* sources = nullptr;
+ ggml_tensor* destination = nullptr;
+ };
+
+ // Reads all targets, batching reads per file. Destinations with the same source receive the
+ // same data from one read.
+ bool read_weights(const std::vector<ReadTarget>& targets);
+
+ // Maps file-backed tensors in place; returns the mappings that keep them valid.
+ std::vector<MmapTensorStore> map_weights(ModelLoader& loader,
+ std::map<std::string, ggml_tensor*>& tensors,
+ bool writable,
+ ggml_backend_dev_t device);
+}
+
+#endif // __SD_WEIGHTS_WEIGHT_READER_H__
diff --git a/src/weights/weight_transfer.cpp b/src/weights/weight_transfer.cpp
new file mode 100644
index 0000000..5524125
--- /dev/null
+++ b/src/weights/weight_transfer.cpp
@@ -0,0 +1,63 @@
+#include "weights/weight_transfer.h"
+
+#include "core/util.h"
+
+namespace sd::weights {
+ ggml_backend_t WeightTransfer::queue_for(ggml_backend_t compute_backend) {
+ auto existing = queues_.find(compute_backend);
+ if (existing != queues_.end())
+ return existing->second;
+ if (compute_backend == nullptr)
+ return nullptr;
+ ggml_backend_dev_t device = ggml_backend_get_device(compute_backend);
+ if (device == nullptr || ggml_backend_dev_type(device) == GGML_BACKEND_DEVICE_TYPE_CPU)
+ return nullptr;
+ ggml_backend_t queue = ggml_backend_dev_init(device, nullptr);
+ if (queue == nullptr) {
+ // Not cached, so a later prefetch retries; warn once per device.
+ if (failed_.insert(compute_backend).second)
+ LOG_WARN("model manager failed to create a prefetch backend for %s", ggml_backend_name(compute_backend));
+ return nullptr;
+ }
+ queues_[compute_backend] = queue;
+ return queue;
+ }
+
+ void WeightTransfer::submit(PendingTransfer& pending, const std::vector<Copy>& copies) {
+ if (pending.submitted || pending.queue == nullptr)
+ return;
+ pending.submitted = true;
+ for (const auto& copy : copies) {
+ if (ggml_backend_buffer_is_host(copy.source->buffer)) {
+ ggml_backend_tensor_set_async(pending.queue, copy.destination, copy.source->data, 0, ggml_nbytes(copy.source));
+ } else {
+ ggml_backend_tensor_copy_async(copy.source_backend, pending.queue, const_cast<ggml_tensor*>(copy.source),
+ copy.destination);
+ }
+ }
+ pending.event = ggml_backend_event_new(ggml_backend_get_device(pending.queue));
+ if (pending.event != nullptr)
+ ggml_backend_event_record(pending.event, pending.queue);
+ }
+
+ void WeightTransfer::wait(PendingTransfer& pending) {
+ if (pending.event != nullptr) {
+ ggml_backend_event_synchronize(pending.event);
+ ggml_backend_event_free(pending.event);
+ pending.event = nullptr;
+ } else if (pending.submitted && pending.queue != nullptr) {
+ ggml_backend_synchronize(pending.queue);
+ }
+ pending.queue = nullptr;
+ pending.submitted = false;
+ }
+
+ void WeightTransfer::release() {
+ for (auto& entry : queues_) {
+ if (entry.second != nullptr)
+ ggml_backend_free(entry.second);
+ }
+ queues_.clear();
+ failed_.clear();
+ }
+}
diff --git a/src/weights/weight_transfer.h b/src/weights/weight_transfer.h
new file mode 100644
index 0000000..45c36b1
--- /dev/null
+++ b/src/weights/weight_transfer.h
@@ -0,0 +1,48 @@
+#ifndef __SD_WEIGHTS_WEIGHT_TRANSFER_H__
+#define __SD_WEIGHTS_WEIGHT_TRANSFER_H__
+
+#include <map>
+#include <set>
+#include <vector>
+
+#include "ggml-backend.h"
+
+namespace sd::weights {
+ // Uploads that run on a compute device's transfer queue while it computes.
+ struct PendingTransfer {
+ ggml_backend_t queue = nullptr;
+ ggml_backend_event_t event = nullptr;
+ bool submitted = false;
+ };
+
+ // Asynchronous weight uploads. The residency layer chooses the copies and owns their buffers;
+ // this class only queues the copies and reports when they are complete.
+ class WeightTransfer {
+ public:
+ struct Copy {
+ const ggml_tensor* source = nullptr;
+ // Backend that owns a device source; RAM sources are uploaded directly.
+ ggml_backend_t source_backend = nullptr;
+ ggml_tensor* destination = nullptr;
+ };
+
+ WeightTransfer() = default;
+ WeightTransfer(const WeightTransfer&) = delete;
+ WeightTransfer& operator=(const WeightTransfer&) = delete;
+ ~WeightTransfer() { release(); }
+
+ // The transfer queue of a compute device; null when the device has none.
+ ggml_backend_t queue_for(ggml_backend_t compute_backend);
+ // Queues the copies on pending.queue and records their completion.
+ void submit(PendingTransfer& pending, const std::vector<Copy>& copies);
+ // Waits for submitted copies; pending can be reused afterwards.
+ static void wait(PendingTransfer& pending);
+ void release();
+
+ private:
+ std::map<ggml_backend_t, ggml_backend_t> queues_;
+ std::set<ggml_backend_t> failed_;
+ };
+}
+
+#endif // __SD_WEIGHTS_WEIGHT_TRANSFER_H__