Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
227 changes: 227 additions & 0 deletions docs/development/weights.md
Original file line number Diff line number Diff line change
@@ -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.
25 changes: 12 additions & 13 deletions docs/dgl.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading