Skip to content

Latest commit

 

History

History
227 lines (191 loc) · 12.4 KB

weights.md

File metadata and controls

227 lines (191 loc) · 12.4 KB

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.

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::Allocations. Each allocation is a real buffer and lists the weight Copys 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.