Skip to content

vllm.distributed.weight_transfer.sharded_rdt_engine

Sharded Ray Direct Transport (RDT) weight transfer engine (consumer side).

Pulls only the slice each vLLM worker consumes under tensor/expert parallelism, not the full HF-format tensor.

Two phases. BAKE, once at init_transfer_engine: drive model.load_weights against FakeRDTTensor placeholders and record, per leaf module, how each destination slice is fetched (an op chain) and where it lands (an as_strided descriptor). REPLAY, every sync: no load_weights, no FakeRDTTensor dispatch, no discovery — pull the recorded slices in packed chunks over a ring of receive buffers, scatter them into freshly materialized params, then quant and kernel-copy. A live name with no recorded plan fails the plan build: there is no fallback load.

Weights arrive in checkpoint format: the engine drives layerwise reload itself, in start_weight_update / finish_weight_update.

Data flow

One thing at four resolutions, over three lifetimes. FetchKey -- (name, op_chain), "which slice of which trainer tensor" -- is the atom; everything else is bookkeeping around it.

BAKE      once at init, kept for the engine's life
  FakeRDTTensor intercepts the model's loaders; each copy_ records a
  _Scatter (sharded_rdt_fake): src FetchKey, owning layer, the destination
  as_strided region, and the produced dtype/nbytes.
    -> _name_to_plan: name -> that module's scatter list

PLAN      once, cached, _build_call_plan
  _Chunk    one packed pull: its scatters, deduped keys, the byte-exact
            pack_layout, which producer serves it, and what to run after
            (materialize / quant / free).  One per (group, owner class).
  _CallPlan all chunks + pre_free.

RUN       per chunk, per sync, _run_chunk_pipeline
  _Chunk -> _PendingPull   issued, not yet landed: Ray ref, buffer views,
                           ring slot.               [RPC thread]
         -> _ProcItem      chunk + results + slot.  [hand-off to the
                           background scatter thread]

The RUN pair stays split on purpose: it is the thread boundary, and only targets should outlive the get -- carrying the Ray ref and the whole-buffer blob into the queue would keep both alive for the scatter's lifetime.

See docs/training/weight_updates/engines/sharded_rdt.md for the design and the measured results behind the choices here.

Classes:

HostStagingAllocationError

Bases: RuntimeError

A host receive slot could not be allocated, page-locked or registered.

ShardedRDTWeightTransferEngine

Bases: WeightTransferEngine[ShardedRDTWeightTransferInitInfo, ShardedRDTWeightTransferUpdateInfo]

Pull-based RDT/NIXL backend that transports only the slice each worker consumes.

Requires distributed_executor_backend="ray", nixl in the shared env, a named trainer actor exposing a @ray.method(tensor_transport="nixl") producer, and weight loaders that stay inside SUPPORTED_OPS — anything needing real data (.to, .item, arithmetic, bool-mask indexing) raises during the bake.

The plan is baked once at init_transfer_engine into one scatter list per fully-loaded leaf module, indexed by source name; every update_weights replays the modules its gathered names cover.

Methods:

  • drain_pending –

    Block until the background thread has processed every queued item and

  • finish_weight_update –

    Drain the deferred pull/process pipeline (so every layer is fully

  • init_transfer_engine –

    Record pool settings, bind producers, bake and build the replay plan,

  • receive_weights –

    Pull + replay the baked leaf modules the sync covers.

  • start_weight_update –

    Put the model's params on meta so layerwise reload streams them in

  • update_weights –

    Receive one update. Unlike the base, does NOT issue a per-update

_alloc_receive_buffer(nbytes, *, state=None, pool_total=None)

Allocate and register one receive buffer in the pool's staging mode. pool_total (init only; a regrow omits it) is named in the failure.

_bake(init_info, state=None)

Bake the replay plan once, as a self-driven meta dry run, into state (the engine itself when omitted).

Puts the params on meta, then drives model.load_weights over init_info.names through the model's ORIGINAL loaders (the stamps bypass online_process_loader, so _layerwise_process is never in the path). Nothing materializes or pulls; the fake's copy_ records the source op chain and the meta destination's geometry. Afterwards one scatter list per fully-loaded leaf module (copied numel == loadable size) is indexed by source name; a partial or unrecordable module fails the plan build. The model is restored.

This leans on layerwise internals a public API should expose first-class: a currently-loading hook instead of monkeypatched stamps, a dry-run mode instead of bypassing online_process_loader, and an abort_layerwise_reload instead of _restore_after_dry_run.

_build_call_plan(names, group_lens, state=None)

Build the STATIC plan for one whole-sync call from the bake and router in state (the engine's own when omitted).

Pure — no pulls, no engine state touched — so the result is cached and reused every sync. Three passes: 1. Split names into gather groups, one chunk per owner class present in this worker's baked copies, recording each group's last chunk for its free_group signal (or pre_free when this worker pulls nothing from it). Every group is signaled exactly once by construction. The stream has no per-group call boundaries, so group L+1's first chunk issues while L's still stream. 2. For modules using layerwise reload, materialize on their FIRST chunk and quant/kernel/reset on their LAST. Modules that opt out receive their slices directly in their existing storage. 3. Assemble _Chunks: dedup keys and precompute the packed layout.

_build_fake_weights(names, sink, device, name_meta)

Zero-storage lazies for names, dtype/shape from the init metadata, all feeding the bake's recording sink.

_build_static_plan(init_info, state=None)

Build the chunk/free plan once, from the bake in state (the engine itself when omitted). It never changes across syncs, so update_weights needs no per-sync names.

_chunk_module_scatters(modules, state=None)

Cut the modules' copies into one chunk per distinct owner class present, ascending by class index, as (class_idx, scatters) pairs.

A chunk is one packed pull, so every name in it must share a producer — which is exactly what an owner class is. The cut is a pure function of the bake and the ownership table (the router in state, the engine's when omitted). Copy order within a chunk is bake order, and a module's copies may span chunks (materialize/quant fire on its first/last chunk; see _build_call_plan).

_commit_init(candidate)

Make a successful attempt's candidate the active state: every field the dataclass lists, so nothing is copied by hand.

_complete_pull(pending)

Blocking half of a pull: the NIXL read lands during this ray.get.

_configure_ring(init_info)

Record the staging/S/K settings; _size_pool applies them once the plan has fixed the effective lane count.

_dispatch_item(item)

Hand one chunk item to the background scatter thread.

Counts the item against its slot BEFORE dispatch: the next pull into that slot must wait until the background thread has processed (and RECORDED the read-done event for) every item ever queued on it.

_ensure_proc_worker(state=None)

Lazily start the post-processing worker: per-slot events, streams, queues and threads. A running worker's handshake carries over into state.

_forget_cached_targets(buffer)

Drop the cached dtype views carved out of buffer.

_global_worker_index()

This worker's stable, distinct global index across the inference fleet: data_parallel_index * world_size + rank over the TP*PP world.

data_parallel_index, not data_parallel_rank: vLLM resets the latter to 0 in a dense worker but keeps the former as the distinct global DP rank. Same formula as the sibling nccl_engine, so dense-via-TP and MoE-via-DP+EP both yield distinct 0..C-1.

_install_recording_stamps(model, recorder)

Wrap each loadable param's weight_loader to stamp recorder.current = (leaf_module, param_name) before delegating to the original loader, so the fake's copy_ can attribute each recorded copy. functools.wraps keeps the loader's real signature (so vLLM's _layerwise_process param redirect still works if a stamp leaks), and _rdt_stamp_inner tags it so _restore_after_dry_run can unwrap it.

_issue_pull(chunk, slot)

Reserve slot, lay the targets out in its buffer, dispatch the produce RPC and point the transfer at the buffer, without the blocking ray.get (_complete_pull), so chunk i+1 is issued before chunk i completes. The slot-reuse wait must precede set_target_for_ref: the transfer may start any time after the metadata push.

_lane_slots(lane)

The contiguous K-slot block owned by one lane.

_mark_slot_done(slot)

Publish that a queued item's read-done event has been recorded (or the item failed) so a pull waiting to reuse slot can proceed to its CUDA-event synchronize.

_num_consumers(state=None)

Total inference-worker count. Prefers the driver-supplied init_info.num_consumers (authoritative -- the driver knows the whole fleet), read from state (the engine itself when omitted); else world_size_across_dp, the same stride _global_worker_index indexes with, so the two agree at any pp.

_park_host_slot(buffer, why, *, exc_info=False)

Keep buffer page-locked and referenced for the process lifetime, at error level: a leaked slot is safe, a freed range still in use is not.

_preregister_at_init(state=None)

Register every NIXL buffer this worker will use, sized from the static plan in state: all LxK receive slots at the largest chunk, and each producer's serve ring at the max bytes this consumer pulls from it.

_proc_worker_loop()

Single persistent thread: run each queued item's process phase on the background stream. Exits on the None sentinel (shutdown). An item that raises is recorded in _proc_error and re-raised on the RPC thread / at drain, so a failed sync fails loudly rather than corrupting silently.

_process_item(item)

Scatter-thread half: materialize this chunk's first-seen modules, scatter its slices on the process stream, publish the slot, then hand the modules it COMPLETES to the quant thread.

Mirrors _layerwise_process minus the loader replay. Once every scatter reading item.slot is enqueued, records the slot's read-done event so the RPC thread can block on it before overwriting the slot.

_pull_targets(chunk, slot, buffer)

Per-key dtype views into slot's buffer.

The packed layout is static, so the views are built once per (chunk, slot) rather than once per pull -- rebuilding them cost ~1150 Python ops per pull at 235B. Keyed on the buffer pointer as well, so a regrow invalidates instead of handing back views into a freed buffer.

_quant_worker_loop()

Dedicated quant thread: drains (completed_modules, scatter-done event) batches. Errors surface via _proc_error like the scatter thread's.

_raise_proc_error()

Re-raise (once) any error captured by the background thread.

_release_attempt_slots(candidate)

Release the host slots a failed init attempt built, i.e. the candidate's tensors the active pool does not hold.

_release_host_slot(buffer)

Give one host slot back: NIXL deregistration, cudaHostUnregister, then drop the cached views. A failure at either step parks the slot instead (it may still be registered). Never raises: it runs on shutdown and in the init rollback.

_release_retired_slots()

Release the host slots a committed re-init grow replaced, once the last scatter out of each has run.

_resolve_consumer_id(init_info, state=None)

This worker's DISTINCT index in 0..C-1 across the whole fleet.

Within one engine that is _global_worker_index(). But a fleet of INDEPENDENT engines (each with its own parallel config) restarts that index at 0 per engine, so each engine offsets into its own range using replica_rank: with a uniform fleet, workers_per_replica = C // num_replicas. num_replicas defaults to 1 (offset 0), preserving single-engine and single-DP-deployment behaviour.

_resolve_producers(init_info, state=None)

Work out this worker's consumer identity, build the router, and bind EVERY producer actor; the router lands in state (the engine itself when omitted).

Pull routing is M:N: each chunk goes to ONE producer holding every name in it (see RdtRouter), so one producer serves a whole pull. All producers are bound regardless, because the per-group free_group signal fans out to every owner of a group, including producers this worker never pulls from.

_restore_after_dry_run(model)

Restore each layerwise layer's saved kernel tensors without pulling (a real finalize_layerwise_reload would materialize/load) and reset its info. Also unwrap any recording stamp left on the params, since a leaked stamp would sit under the next sync's online_process_loader and silently break _layerwise_process's param redirect.

_run_chunk_pipeline(plan)

Pull stage streams through independent K-deep FIFO lanes.

Slot safety rests on two arguments spelled out in the doc: the producer's ring is no shallower than a lane's window and FIFO drain-before-issue orders its reuse; the consumer's slots are held by _issue_pull's generation handshake.

_run_quant(layers, ready)

Quant/kernel-copy/reset the given COMPLETED leaf modules through the same _process_loaded_layer as _layerwise_process. Runs on the quant thread's own stream, ordered after the modules' scatters via ready; touches only the scattered params (never a receive slot), so it can overlap subsequent chunks' RDMA and scatters. The info.reset() in there is what makes finalize skip the layer — drain_pending joins the quant queue before finalize runs.

_signal_group_done(group_idx)

Fire-and-forget free_group signal at EVERY owner of the group.

The per-group barrier: each owner counts one signal per live consumer and frees the group (releasing its lookahead credit) on the last one, so every owner must hear from every consumer — including owners this worker pulls nothing from. Refs are held and drained in drain_pending so every signal has EXECUTED before the sync ends: begin_sync resets the counters, and a straggler landing in the next sync would credit a group it does not belong to.

_size_pool(config, plan, state=None)

Lay out the LxK receive pool into state (the engine when omitted). Once the worker exists, a re-init must keep the (staging_device, L, K) geometry, and then reuses the active slots and lane cursors.

_slot_free(slot)

Whether a pull into slot can start without waiting.

_wait_any_head(pulls, timeout=None)

Return the index of a landed pull, or None after timeout.

_wait_slot_consumed(slot)

_wait_slot_free for release paths, where the worker may be gone.

_wait_slot_free(slot, worker_alive)

Block until every scatter out of slot has run. Both waits are needed: the generation wait (only while a worker is alive to publish done counts) ensures this use's read-done event was recorded, since the event binds to its LAST record; the event wait ensures the GPU read finished.

_workers_per_replica(init_info, state=None)

Consumers per inference deployment, assuming a uniform fleet.

Read by this worker's consumer id and by the router's block carve, which must not disagree, so it is derived once here.

drain_pending()

Block until the background thread has processed every queued item and its stream work is complete, then re-raise any error it hit. Called from the worker's finish_weight_update before finalize_layerwise_reload so every baked layer is fully loaded (and info.reset()-ed) first.

finish_weight_update()

Drain the deferred pull/process pipeline (so every layer is fully loaded) before finalizing the layerwise reload.

init_transfer_engine(init_info)

Record pool settings, bind producers, bake and build the replay plan, size its LxK receive pool, then pre-register every NIXL buffer.

The bake drives model.load_weights and the pre-registration blocks on RPCs to the producers, so this is a heavyweight one-off; every later update_weights is pure replay.

receive_weights(update_info)

Pull + replay the baked leaf modules the sync covers.

The chunk/free plan is STATIC across syncs — a pure function of the baked plan and the driver's group partition — so it was built once at init and every sync just re-runs the pipeline over its self-describing chunks. The update carries only the sync index used to tag free signals: an int at or above -1 (-1 means untagged); anything else is a malformed payload and fails the sync before a signal goes out.

Assumes each baked module's source names fall within one gather group, which the per-layer / pre / post partition guarantees (a leaf module's sources all live in one decoder layer). A module that did span groups would be planned once per group and could pull a name whose group the pipeline already freed, which parks the pull until the producer's stall watchdog fires.

start_weight_update()

Put the model's params on meta so layerwise reload streams them in as each layer's slices land. Baked replay uses checkpoint format.

update_weights(update_info)

Receive one update. Unlike the base, does NOT issue a per-update device sync: post-processing is deferred to background threads and a sync here would block on them and serialize the pull/process pipeline. Completion is guaranteed by drain_pending in finish_weight_update.

ShardedRDTWeightTransferInitInfo dataclass

Bases: WeightTransferInitInfo

Initialization info for the sharded RDT backend.

Attributes:

buffer_presize_gb = 0.0 class-attribute instance-attribute

Pre-size each packed receive-buffer slot to this many GiB (0 = size to the first chunk + coarse 256MB round-up). Set it to cover the model's largest atomic chunk (e.g. an untied lm_head). Sizing buffers ONCE matters beyond perf -- see the doc's "Sizing buffers once matters beyond throughput".

dtype_names = field(default_factory=list) class-attribute instance-attribute

Dtype name (e.g. 'bfloat16') for each entry of names.

group_lens = field(default_factory=list) class-attribute instance-attribute

Partition of names into gather groups, in the SAME order the trainers gather and publish them (group-major; sum(group_lens) == len(names), and names must be ordered to match). Required: the engine pre-builds the whole static chunk/signal plan from it at init, and fires free_group at every owner as each group's last chunk completes.

name_owner_class = field(default_factory=list) class-attribute instance-attribute

Per-name index into owner_sets, parallel to names: which producers hold each name. Empty means every producer holds every name.

This one table expresses every layout the trainer can have — pipeline stages (the names of these groups have this owner set), expert parallelism (this expert name has this one-rank owner set), and combinations of the two — so the engine cuts each group's baked copies into one chunk per distinct class present and routes each chunk to that class's owner. Derived by the trainer from ParamMeta.owners.

names = field(default_factory=list) class-attribute instance-attribute

The trainer's complete, flat param name list. The bake drives model.load_weights over all of them once and keys the plan by source name.

num_consumers = 0 class-attribute instance-attribute

Total consumer count across the fleet, for M:N routing. Authoritative when

0; at 0 the engine infers it from parallel_config, which is correct for the supported serving modes but worth setting explicitly under M:N. Each worker's distinct index comes from _global_worker_index.

num_rdt_buffers = 2 class-attribute instance-attribute

K, the receive slots and in-flight pulls per active stream lane. Must match the producer's ring depth. The consumer pool is L x K slots, where L is the effective stages_in_flight clamped to the plan's stream count. Keep K x chunk_bytes per flow under the fabric's address-translation reach (~2-3 GB/flow on the reference 8xB200 RoCE cluster).

num_replicas = 1 class-attribute instance-attribute

Number of independent inference engines in the fleet. Default 1 => the per-replica offset is 0 and consumer identity is exactly _global_worker_index (preserves single-engine and single-DP-deployment behavior). When > 1, workers_per_replica = num_consumers // num_replicas and this engine's consumers occupy replica_rank * workers_per_replica + _global_worker_index(). Assumes a uniform fleet (every replica has the same worker count). Set alongside replica_rank, by the driver.

owner_sets = field(default_factory=list) class-attribute instance-attribute

The distinct producer sets that occur, each a sorted list of trainer ranks (indices into trainer_actor_names). Indexed by name_owner_class. Empty means every producer holds every name.

produce_method_name = 'rdt_produce_weights_batched' class-attribute instance-attribute

Name of the trainer-side producer method. It and the rest of the serve surface (free_group, reserve_serve_buffer) are documented where they are implemented, on _RDTProducerServer in sharded_rdt_trainer.py.

replica_rank = 0 class-attribute instance-attribute

This inference engine's ordinal in the fleet (0..num_replicas-1).

Multi-engine deployments run several INDEPENDENT inference engines, each with its own self-contained parallel config, so every engine's _global_worker_index restarts at 0 and would collide across engines. The driver gives each engine a distinct replica_rank (with identical num_replicas) so the engine offsets its consumers into a globally distinct range for the M:N block assignment.Default 0/1 (single engine) needs no override.

shapes = field(default_factory=list) class-attribute instance-attribute

Full HF shape for each entry of names.

stages_in_flight = 1 class-attribute instance-attribute

Maximum trainer stages pulled from concurrently.

staging_device = 'gpu' class-attribute instance-attribute

Where receive buffers live: GPU HBM or pinned host memory.

trainer_actor_names = field(default_factory=list) class-attribute instance-attribute

Names of all trainer Ray actors exposing the producer method (set via .options(name=...)), ordered by trainer rank. RdtRouter picks one of them per pull, out of the name's owner set. Every actor is bound regardless, because free_group fans out to every owner. Must be non-empty; a single-producer trainer passes a one-element list.

trainer_actor_namespace = None class-attribute instance-attribute

Optional Ray namespace the trainer actor(s) live in.

ShardedRDTWeightTransferUpdateInfo dataclass

Bases: WeightTransferUpdateInfo

Update info for the sharded RDT backend: the sync's index, nothing else.

The chunk/free plan is a pure function of the baked plan and the driver's gather-group partition, both fixed for the engine's lifetime, so it is built once at init_transfer_engine from ShardedRDTWeightTransferInitInfo's names + group_lens. ONE update_weights per sync then just re-runs that plan.

Attributes:

  • sync_idx (int) –

    The trainer's count of this sync, sent with every free_group so a

sync_idx = -1 class-attribute instance-attribute

The trainer's count of this sync, sent with every free_group so a producer that has not begun the sync yet keeps the signal instead of losing it to its begin_sync. -1 (an older trainer) sends untagged signals.

_CallPlan dataclass

The static plan for one sync (see Data flow). Pure, so it is built once and reused; runtime is then execution only.

pre_free = groups with NO chunk on this worker, signaled at sync start (owners tolerate a signal preceding its publish). With the last-chunk signals this keeps the completeness invariant consumer-local: every group is signaled exactly once.

_Chunk dataclass

One packed pull plus its post-processing (see Data flow).

A module's copies span chunks when its experts sit in several owner classes, so materialize fires on its FIRST chunk and quant on its LAST -- materialize-once by construction, not by a runtime counter. pack_layout mirrors the producer's rule byte-exactly.

_InitCandidate dataclass

The state one init_transfer_engine attempt builds, under the engine's own attribute names: _commit_init copies every field onto the engine on success, and a failed attempt is simply dropped.

_PendingPull dataclass

A dispatched pull whose blocking ray.get has not run (see Data flow).

targets/blob must stay strongly referenced until it completes: set_target_for_ref stores WEAKREFS, so dropping them silently reroutes the transfer into a fallback buffer.

_ProcItem dataclass

A landed pull handed to the background scatter thread (see Data flow).

results alias the ring buffer slot, held as strong refs so they outlive the RPC-thread frame until the scatter consumes them.

_PullHooks dataclass

Operations injected into the pure _run_lanes scheduler.

_ReceivePoolConfig dataclass

Validated receive-pool settings recorded before the plan is known.

_alloc_page_locked_slot(nbytes, *, park)

One exact-size host receive slot: pageable memory page-locked whole with cudaHostRegister (torch's pinned allocator rounds and caches), then NIXL-registered. A failure leaves no registration behind: a NIXL error unregisters the range first, or parks it when that rollback fails too.

_check_streams(chunks)

Refuse streams that split a leaf module's loading, which would break its materialize-first, quant-last order. Owners and gather groups need no check: _build_call_plan gives each owner component one stream by construction.

_cuda_error_text(cudart, code)

cudaGetErrorString for a raw code: the wrapper's cudaHost* calls return plain ints while its cudaGetErrorString is typed on cudaError_t, a ctypes.c_int the runtime accepts an int for.

_dtype_from_name(name)

Resolve a string like 'bfloat16' to torch.bfloat16.

_host_alloc_request(pool, nbytes, pool_total)

The failed host allocation with its pool geometry: the whole pool at init, or one regrown slot (pool_total None) in _issue_pull.

_host_unregister(cudart, base)

Undo cudaHostRegister on base; True when it succeeded. A failure is logged, not raised: this runs on shutdown and inside the init rollback, and the caller decides the range's fate.

_plan_digest(keys_per_chunk)

Digest of the chunks one consumer pulls from one producer, in pull order.

Two consumers a producer serves out of ONE shared serve ring must agree on this, since sharing rests on their plans being identical; the producer compares it at init. Over the whole (name, op-chain) list rather than the names, because the chains decide the bytes each pull returns.

_run_lanes(streams, *, depth, blocks, cursors, hooks)

Run one K-deep FIFO pull window per disjoint slot block.

A lane takes the next unstarted stream after issuing its current stream's last chunk, so its window spans the handoff. If a lane is waiting for slot reuse while other lane heads are outstanding, the head wait is bounded: shared producer packs can otherwise deadlock while each replica waits for a pull that another replica has not yet issued.

_stage_components(router, names, group_lens)

Return each producer's connected owner component.

Producers are connected when they co-own names in one gather group. Pure pipeline stages therefore form separate components, while a cross-stage group conservatively merges its stages into one ordered stream.