vllm.distributed.weight_transfer.base ¶
Base class for weight transfer engines.
Classes:
-
ModuleSource–WeightSourceovermodule.named_parameters()— the common case. -
ParamMeta–Name / wire dtype / full (HF) shape for one output parameter.
-
TrainerInitInfo–Base trainer-side init info: which trainer rank drives the transfer.
-
TrainerWeightTransferEngine–Trainer-side weight transfer engine.
-
VLLMWeightSyncClient–Trainer-side stub for the inference engine's weight-sync control plane.
-
WeightSource–A re-iterable source of the trainer's weights, handed to a trainer engine.
-
WeightTransferEngine–Base class for weight transfer engines that handle transport of model weights
-
WeightTransferInitInfo–Base class for backend-specific initialization info.
-
WeightTransferInitRequest–API-level weight transfer initialization request.
-
WeightTransferUpdateInfo–Base class for backend-specific weight update info.
-
WeightTransferUpdateRequest–API-level weight update request.
Functions:
-
layerwise_groups–Partition flat parameter names into one group per decoder layer, keyed on
-
materialize_full_tensor–Return a full, locally-materialized tensor ready to send.
ModuleSource ¶
Bases: WeightSource
WeightSource over module.named_parameters() — the common case.
Handles both plain dense modules and FSDP-sharded ones with no special casing: iteration all-gathers each DTensor via full_tensor() (a collective) and passes regular tensors through. metadata() reads the global .shape / .dtype, so it never triggers a gather.
Source code in vllm/distributed/weight_transfer/base.py
ParamMeta dataclass ¶
Name / wire dtype / full (HF) shape for one output parameter.
Source code in vllm/distributed/weight_transfer/base.py
TrainerInitInfo dataclass ¶
Base trainer-side init info: which trainer rank drives the transfer.
rank is this trainer process's rank, provided explicitly by the caller — the engine does not read it from a global process group, which is ambiguous once several groups (FSDP / TP / PP / EP) exist. Rank 0 is always the sender: only it opens the endpoint and drives the inference-side RPCs, while every rank still runs the trainer-side collectives. Backend subclasses add their own (positional) fields; rank is keyword-only so that ordering never conflicts.
Every concrete subclass sets a class-level backend string (the same key it registers under in WeightTransferTrainerFactory). The factory reads it to dispatch, so callers pass only the init info/ It is a ClassVar (a fixed per-backend constant), so it is not an __init__ field.
Source code in vllm/distributed/weight_transfer/base.py
TrainerWeightTransferEngine ¶
Bases: ABC, Generic[TTrainerInitInfo]
Trainer-side weight transfer engine.
Symmetric to WeightTransferEngine but lives in the training process. Constructed via the trainer_init factory classmethod; carries any backend-specific state (NCCL communicators, IPC device info, transfer plans) on self. Full-resync backends (NCCL, IPC) take a WeightSource at trainer_init and replay it each round via the no-argument send_weights(). Backends that push per-round deltas instead (e.g. sparse patches) leave source as None and take their payload as a send_weights argument.
Unlike the worker engine, the trainer side does not take a WeightTransferConfig: the backend is selected from the init info's backend ClassVar (so callers pass only the init info), and the static wire params (packed, buffer sizes) ride the backend-specific TrainerInitInfo, which the sender also propagates to the worker at the init handshake.
Multi-rank trainers: trainer_init and send_weights are called on every trainer rank. Rank 0 is the sender, resolved once at trainer_init into is_sender. Non-sender ranks still run every collective (iterating the source, metadata export, IPC handle all-gather) so the group stays aligned, but each engine explicitly guards the control-plane RPCs and the transmit on self.is_sender, so only the sender touches the client.
Subclasses should define
init_info_cls: Type of backend-specific trainer init info
Methods:
-
send_weights–Push weights to inference workers and drive the full update round
-
shutdown–Tear down communicators / process groups. Default no-op.
-
trainer_init–Rendezvous with the inference side and return a ready instance.
Source code in vllm/distributed/weight_transfer/base.py
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 | |
send_weights() abstractmethod ¶
Push weights to inference workers and drive the full update round trip: start_weight_update, update_weights (run concurrently with the trainer-side broadcast when the backend requires it), then finish_weight_update. Called on every trainer rank.
Source code in vllm/distributed/weight_transfer/base.py
shutdown() ¶
trainer_init(init_info, *, client, source=None) abstractmethod classmethod ¶
Rendezvous with the inference side and return a ready instance.
Called on every trainer rank. The sender drives the full handshake via client (build the worker-side init info, call client.init_weight_transfer_engine, open the trainer-side endpoint); non-sender ranks skip the rendezvous and the RPC.
Source code in vllm/distributed/weight_transfer/base.py
VLLMWeightSyncClient ¶
Bases: Protocol
Trainer-side stub for the inference engine's weight-sync control plane.
Mirrors the weight-sync methods that the inference engine exposes (EngineClient / the HTTP RLHF routes / Ray actors). A TrainerWeightTransferEngine drives the full handshake through this protocol so trainer code never has to know the transport.
All methods are synchronous and accept plain dicts (matching what the inference side already accepts). Concurrency that some backends need (e.g. NCCL must run update_weights concurrently with the trainer-side broadcast) is the engine's responsibility, not the client's, so the protocol stays a flat four-method surface that any wrapper can implement.
The protocol is structural (PEP 544), so user implementations need only define these four methods — no import or subclassing required.
Source code in vllm/distributed/weight_transfer/base.py
WeightSource ¶
Bases: ABC
A re-iterable source of the trainer's weights, handed to a trainer engine.
Two channels:
metadata()—(name, wire dtype, full shape)for every parameter, without transferring. Cheap when shapes are known locally (FSDPDTensorglobal shape); may be expensive on first call for backends that must materialize to learn shapes (e.g. a Megatron-Bridge export), in which case it should cache.- iteration — yields fully-materialized
(name, tensor)pairs, one at a time. Materializing is typically a collective (FSDPfull_tensor(), a Megatron export), so the ranks that share a parameter must iterate it in the same order in lockstep, or they deadlock. held_names()— which parameters this rank holds, for producers that are split so each rank holds only part of the model. Defaults to all.iter_groups()— the same stream batched per gather group (seelayerwise_groups). Defaults to batching__iter__; override to materialize a whole group in one step.
iter(source) must yield a fresh pass each round. Backends with custom producer logic (Megatron export, RDT plans, MoE re-fusing) subclass this.
Methods:
-
groups–This rank's gather groups, in metadata order:
layerwise_groupsover -
held_names–The parameters this rank holds, or None for all of them.
-
iter_groups–Yield one
(names, tensors)batch per group fromgroups(). -
metadata–Declare what iteration will yield, without transferring anything.
Source code in vllm/distributed/weight_transfer/base.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
groups() ¶
This rank's gather groups, in metadata order: layerwise_groups over metadata(), restricted to the groups holding at least one held name.
A group with nothing held here is not iterated at all — its gather is a collective among the ranks that do hold part of it.
Source code in vllm/distributed/weight_transfer/base.py
held_names() ¶
The parameters this rank holds, or None for all of them.
This is the whole ownership contract. Override it when producers are split so each holds only part of the model — pipeline parallelism (a rank holds some layers), expert parallelism (a rank holds some experts), or any combination, including layouts that fit neither. A consumer routes each name to a rank that holds it, so per-name is the granularity that matters; the engine derives everything else from this.
Three requirements come with overriding it:
metadata()must still describe the WHOLE model on every rank. The group partition, the iteration checks and the consumers' pull plans are all built from one rank's metadata, so a rank that reported only its own share would leave the rest of the model silently un-transferred. The sharded-RDT engine cross-checks this across ranks at init.- Every name must be held by at least one rank, or it can never be served. The engine raises at init naming the first orphan.
- Iteration must cover exactly
groups()in metadata order, yielding a real tensor for each held name andNonefor the rest. A group's gather is a collective among the ranks that hold part of it, so the name must still appear (to keep the order check aligned) while the data is absent.
Returns:
-
Collection[str] | None–The held parameter names, or None to hold every one.
Source code in vllm/distributed/weight_transfer/base.py
iter_groups() ¶
Yield one (names, tensors) batch per group from groups().
The default drives __iter__ and batches its output, checking as it goes that the names arrive in metadata order — ranks sharing a parameter materialize it with a collective, so a rank that iterates out of order deadlocks its peers rather than returning wrong data.
Override when a backend can produce a whole group at once. Materializing is usually a collective, and driving it per group instead of per tensor turns ~37k generator resumes into ~95 on a per-expert MoE model (worth ~0.9s per sync there). An override must yield the same batches in the same order as this default.
Source code in vllm/distributed/weight_transfer/base.py
metadata() abstractmethod ¶
Declare what iteration will yield, without transferring anything.
Must agree with iteration element for element: the same parameters, in the same order, with the same dtypes and shapes. Backends may read both channels and trust that they match (dense NCCL sizes the worker's receive buffers and its packed chunk boundaries from this, then sends the bytes from iteration), so a source that disagrees between the two splits the stream differently on each side.
Source code in vllm/distributed/weight_transfer/base.py
WeightTransferEngine ¶
Bases: ABC, Generic[TInitInfo, TUpdateInfo]
Base class for weight transfer engines that handle transport of model weights from a trainer to inference workers.
This abstraction separates weight transfer transport logic from the worker implementation, allowing different backends (NCCL, CUDA IPC, RDMA[TODO]) to be plugged in.
Each engine owns its full weight-update lifecycle: start_weight_update, update_weights, and finish_weight_update. Layerwise reloading (used by checkpoint-format engines) is opted into per engine by running it inside start_weight_update/finish_weight_update. Engines that apply weights in place (e.g. sparse patches) leave those methods as no-ops.
Subclasses should define
init_info_cls: Type of backend-specific initialization info update_info_cls: Type of backend-specific update info
Methods:
-
__init__–Initialize the weight transfer engine.
-
drain_pending–Block until every deferred update has been applied to the model.
-
finish_weight_update–Finalize the current weight update.
-
init_transfer_engine–Initialize the weight transfer mechanism.
-
parse_init_info–Construct typed init info from dict with validation.
-
parse_update_info–Construct typed update info from dict with validation.
-
receive_weights–Receive weights from the trainer and load them into the model.
-
reset_weight_update_target–Restore weight updates to the engine's default target model.
-
set_weight_update_target–Set the model that will receive the active weight update.
-
shutdown–Shutdown the weight transfer engine.
-
start_weight_update–Prepare the engine for a new weight update.
-
update_weights–Receive one weight update chunk and load it into the model.
Attributes:
-
defers_processing(bool) –Whether
update_weightsreturns before the weights are on the device.
Source code in vllm/distributed/weight_transfer/base.py
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | |
defers_processing = False class-attribute instance-attribute ¶
Whether update_weights returns before the weights are on the device.
An engine that pipelines its GPU post-processing onto background threads cannot let update_weights synchronize the device — that would block on those threads and serialize the pipeline. Such an engine sets this True, omits the per-update sync, and guarantees completion in finish_weight_update instead.
Callers that go through finish_weight_update need do nothing: the engine drains there. A caller that instead drives the tail itself — running its own finalize_layerwise_reload, say — must read this flag and call drain_pending() first, because with it set a returned update_weights means "queued", not "applied".
__init__(config, vllm_config, device, model) ¶
Initialize the weight transfer engine.
Parameters:
-
(config¶WeightTransferConfig) –The configuration for the weight transfer engine
-
(vllm_config¶VllmConfig) –The full vLLM config (provides parallel/model config)
-
(device¶device) –The device this worker's model lives on
-
(model¶Module) –The local model instance which will receive the weights
Source code in vllm/distributed/weight_transfer/base.py
drain_pending() ¶
Block until every deferred update has been applied to the model.
The companion to defers_processing: a caller that has taken over the update tail calls this to re-establish the guarantee that finish_weight_update would otherwise have given it. Idempotent, and a no-op by default — an engine that processes synchronously has nothing to drain, so this is always safe to call.
Source code in vllm/distributed/weight_transfer/base.py
finish_weight_update() abstractmethod ¶
Finalize the current weight update.
Checkpoint-format engines finalize layerwise reloading here; engines that apply weights in place leave this as a no-op.
Source code in vllm/distributed/weight_transfer/base.py
init_transfer_engine(init_info) abstractmethod ¶
Initialize the weight transfer mechanism. This is called once at the beginning of training.
Parameters:
-
(init_info¶TInitInfo) –Backend-specific initialization info
Source code in vllm/distributed/weight_transfer/base.py
parse_init_info(init_dict) ¶
Construct typed init info from dict with validation.
Parameters:
Returns:
-
TInitInfo–Typed backend-specific init info dataclass
Raises:
-
ValueError–If init_dict is invalid for this backend
Source code in vllm/distributed/weight_transfer/base.py
parse_update_info(update_dict) ¶
Construct typed update info from dict with validation.
Parameters:
Returns:
-
TUpdateInfo–Typed backend-specific update info dataclass
Raises:
-
ValueError–If update_dict is invalid for this backend
Source code in vllm/distributed/weight_transfer/base.py
receive_weights(update_info) abstractmethod ¶
Receive weights from the trainer and load them into the model.
Parameters:
-
(update_info¶TUpdateInfo) –Backend-specific update info containing parameter metadata and any backend-specific data
Source code in vllm/distributed/weight_transfer/base.py
reset_weight_update_target() ¶
Restore weight updates to the engine's default target model.
set_weight_update_target(model, model_config) ¶
Set the model that will receive the active weight update.
shutdown() abstractmethod ¶
Shutdown the weight transfer engine. This should be called when the worker is shutting down.
start_weight_update() abstractmethod ¶
Prepare the engine for a new weight update.
Engines that receive weights in checkpoint format initialize layerwise reloading here, else this is typically a no-op. See: https://docs.vllm.ai/en/latest/training/layerwise/ for more details.
Source code in vllm/distributed/weight_transfer/base.py
update_weights(update_info) ¶
Receive one weight update chunk and load it into the model.
Parameters:
Source code in vllm/distributed/weight_transfer/base.py
WeightTransferInitInfo dataclass ¶
WeightTransferInitRequest dataclass ¶
WeightTransferUpdateInfo dataclass ¶
WeightTransferUpdateRequest dataclass ¶
_stack_key(name) ¶
(prefix, index) of the OUTERMOST integer segment, or None if there is none.
Outermost is what keeps a MoE layer whole: model.layers.3.mlp.experts.7.w1 keys on the layer, not the expert.
Source code in vllm/distributed/weight_transfer/base.py
layerwise_groups(names) ¶
Partition flat parameter names into one group per decoder layer, keyed on the outermost index segment of each name.
This defines what a group index means for WeightSource.groups and WeightSource.iter_groups: index g names the same group on every trainer rank and every consumer, because it is derived from one rank's metadata() order.
Keying on the index rather than a literal prefix needs no per-architecture naming table: model.layers.0., model.language_model.layers.0., transformer.h.0., backbone.layers.0. and a vision tower's visual.blocks.0. all partition alike. Matching one fixed prefix does not, and its failure is silent — every name lands in a single group holding the whole model, which defeats the per-layer bound below.
Un-indexed names split by POSITION relative to the first indexed one: the pre block (embeddings) and the post block (the final norm, lm_head, and any inter-stack projector). Post lands last however early it arrived, which is what a pipeline-parallel source needs — Megatron-Bridge streams the last stage's output block before its layers.
Stacks come out in first-appearance order of their prefix and ascending index within it, whatever order the source yielded them, so a source can normalize an arbitrary export order by flattening this partition.
Backends that gather and free per group (sharded RDT) also use it as the unit of transfer, which bounds their buffer sizes: without it a whole model becomes one chunk.
Source code in vllm/distributed/weight_transfer/base.py
materialize_full_tensor(tensor) ¶
Return a full, locally-materialized tensor ready to send.
FSDP shards (DTensors) expose full_tensor(), a collective all-gather; regular tensors do not and are returned unchanged. Trainer engines call this at send time so the (potentially expensive) gather happens exactly once — reading .shape/.dtype for metadata does not trigger it.