[feat] Add explicit /start_weight_update and /finish_weight_update APIs for weight transfer (#39212)

This commit is contained in:
Sumanth R Hegde
2026-05-08 18:03:33 -07:00
committed by GitHub
parent 30f519e947
commit e3b65a5ba0
19 changed files with 287 additions and 53 deletions
+2 -6
View File
@@ -4,7 +4,7 @@
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterator
from dataclasses import KW_ONLY, dataclass, field
from dataclasses import dataclass, field
from typing import Any, Generic, TypeVar
import torch
@@ -28,11 +28,7 @@ class WeightTransferInitInfo(ABC): # noqa: B024
class WeightTransferUpdateInfo(ABC): # noqa: B024
"""Base class for backend-specific weight update info."""
_: KW_ONLY
is_checkpoint_format: bool = True
"""Set to True if weights are in checkpoint/original model format and need
layerwise processing. Set to False if weights have already been processed
into kernel format (repacking, renaming, etc.)."""
pass
# API-level request classes (accept dicts for backend-agnostic serialization)
@@ -211,6 +211,11 @@ class IPCWeightTransferEngine(
- 'ray': Sends weights via Ray RPC to a Ray-based LLM handle
- 'http': Sends weights via HTTP POST to a vLLM HTTP server
.. note::
This method calls ``update_weights`` internally. The caller must
call ``start_weight_update`` before and ``finish_weight_update``
after this method.
Args:
iterator: Iterator of model parameters. Returns (name, tensor) tuples.
Tensors should be on the same GPU as the inference workers.
+8
View File
@@ -230,6 +230,14 @@ class EngineClient(ABC):
"""Initialize weight transfer for RL training."""
raise NotImplementedError
async def start_weight_update(self, is_checkpoint_format: bool = True) -> None:
"""Start a new weight update."""
raise NotImplementedError
async def update_weights(self, request: WeightTransferUpdateRequest) -> None:
"""Batched weight update for RL training."""
raise NotImplementedError
async def finish_weight_update(self) -> None:
"""Finish the current weight update."""
raise NotImplementedError
+20
View File
@@ -1908,6 +1908,20 @@ class LLM:
"init_weight_transfer_engine", kwargs={"init_info": init_info_dict}
)
def start_weight_update(self, is_checkpoint_format: bool = True) -> None:
"""
Start a new weight update.
Args:
is_checkpoint_format: Whether incoming weights are in checkpoint
format (need layerwise processing) or kernel format (direct
copy).
"""
self.llm_engine.collective_rpc(
"start_weight_update",
kwargs={"is_checkpoint_format": is_checkpoint_format},
)
def update_weights(self, request: WeightTransferUpdateRequest | dict) -> None:
"""
Update the weights of the model.
@@ -1923,6 +1937,12 @@ class LLM:
"update_weights", kwargs={"update_info": update_info_dict}
)
def finish_weight_update(self) -> None:
"""
Finish the current weight update.
"""
self.llm_engine.collective_rpc("finish_weight_update")
def __repr__(self) -> str:
"""Return a transformers-style hierarchical view of the model."""
# Cache the result to avoid repeated collective_rpc calls
+19
View File
@@ -128,6 +128,19 @@ async def init_weight_transfer_engine(raw_request: Request):
return JSONResponse(content={"message": "Weight transfer initialized"})
@router.post("/start_weight_update")
async def start_weight_update(raw_request: Request):
try:
body = await raw_request.json()
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="Invalid JSON format") from e # noqa: B904
is_checkpoint_format = body.get("is_checkpoint_format", True)
await engine_client(raw_request).start_weight_update(
is_checkpoint_format=is_checkpoint_format
)
return JSONResponse(content={"message": "Weight update started"})
@router.post("/update_weights")
async def update_weights(raw_request: Request):
try:
@@ -146,6 +159,12 @@ async def update_weights(raw_request: Request):
return JSONResponse(content={"message": "Weights updated"})
@router.post("/finish_weight_update")
async def finish_weight_update(raw_request: Request):
await engine_client(raw_request).finish_weight_update()
return JSONResponse(content={"message": "Weight update finished"})
@router.get("/get_world_size")
async def get_world_size(
raw_request: Request,
+11
View File
@@ -1049,6 +1049,13 @@ class AsyncLLM(EngineClient):
"init_weight_transfer_engine", kwargs={"init_info": init_info_dict}
)
async def start_weight_update(self, is_checkpoint_format: bool = True) -> None:
"""Start a new weight update."""
await self.collective_rpc(
"start_weight_update",
kwargs={"is_checkpoint_format": is_checkpoint_format},
)
async def update_weights(self, request: WeightTransferUpdateRequest) -> None:
"""
Batched weight update for RL training.
@@ -1067,3 +1074,7 @@ class AsyncLLM(EngineClient):
await self.collective_rpc(
"update_weights", kwargs={"update_info": update_info_dict}
)
async def finish_weight_update(self) -> None:
"""Finish the current weight update."""
await self.collective_rpc("finish_weight_update")
+97 -31
View File
@@ -140,6 +140,8 @@ class Worker(WorkerBase):
if self.vllm_config.weight_transfer_config is not None
else None
)
self._weight_update_active = False
self._is_checkpoint_format = True
# Torch/CUDA profiler. Enabled and configured through profiler_config.
# Profiler wrapper is created lazily in profile() when start is called,
@@ -966,6 +968,13 @@ class Worker(WorkerBase):
model_config=self.model_config,
)
def _check_weight_transfer_engine(self) -> None:
if self.weight_transfer_engine is None:
raise RuntimeError(
"Weight transfer not configured. "
"Please set weight_transfer_config to enable weight transfer."
)
def init_weight_transfer_engine(self, init_info: dict) -> None:
"""
Initialize weight transfer mechanism.
@@ -974,26 +983,62 @@ class Worker(WorkerBase):
Args:
init_info: Dictionary containing backend-specific initialization info
"""
if self.weight_transfer_engine is None:
raise RuntimeError(
"Weight transfer not configured. "
"Please set weight_transfer_config to enable weight transfer."
)
self._check_weight_transfer_engine()
assert self.weight_transfer_engine is not None
# Parse dict into backend-specific typed dataclass
typed_init_info = self.weight_transfer_engine.parse_init_info(init_info)
self.weight_transfer_engine.init_transfer_engine(typed_init_info)
def start_weight_update(self, is_checkpoint_format: bool = True) -> None:
"""
Start a new weight update.
Prepares the model for receiving weights. For checkpoint format,
this initializes state for layerwise processing. For kernel format, this is
a no-op but must still be called for consistency.
Args:
is_checkpoint_format: Whether incoming weights are in checkpoint
format (need layerwise processing) or kernel format (direct
copy). Stored as state for finish_weight_update.
"""
self._check_weight_transfer_engine()
if self._weight_update_active:
raise RuntimeError(
"start_weight_update called while a weight update is "
"already active. Call finish_weight_update first."
)
if is_checkpoint_format:
from vllm.model_executor.model_loader.reload import (
initialize_layerwise_reload,
)
model = self.model_runner.model
with torch.device(self.device):
initialize_layerwise_reload(model)
# Store state so update_weights/finish_weight_update can check
self._is_checkpoint_format = is_checkpoint_format
self._weight_update_active = True
def update_weights(self, update_info: dict) -> None:
"""
Batched weight update from the trainer.
Receive weights from the trainer (one or more chunks).
start_weight_update must be called before update_weights and
finish_weight_update must be called after.
Args:
update_info: Dictionary containing backend-specific update info
"""
if self.weight_transfer_engine is None:
self._check_weight_transfer_engine()
assert self.weight_transfer_engine is not None
if not self._weight_update_active:
raise RuntimeError(
"Weight transfer not configured. "
"Please set weight_transfer_config to enable weight transfer."
"start_weight_update must be called before update_weights."
)
# Parse dict into backend-specific typed dataclass
@@ -1001,38 +1046,59 @@ class Worker(WorkerBase):
model = self.model_runner.model
if typed_update_info.is_checkpoint_format:
from vllm.model_executor.model_loader.reload import (
finalize_layerwise_reload,
initialize_layerwise_reload,
)
# Use layerwise reload pattern for checkpoint format weights
with torch.device(self.device):
initialize_layerwise_reload(model)
with torch.device(self.device):
if self._is_checkpoint_format:
self.weight_transfer_engine.receive_weights(
typed_update_info,
load_weights=model.load_weights,
)
finalize_layerwise_reload(model, self.model_config)
else:
# Weights are already in kernel format, copy directly
def load_weights_direct(
weights: list[tuple[str, torch.Tensor]],
) -> None:
for name, weight in weights:
param = model.get_parameter(name)
param.copy_(weight)
else:
# Weights are already in kernel format, copy directly
def load_weights_direct(
weights: list[tuple[str, torch.Tensor]],
) -> None:
for name, weight in weights:
param = model.get_parameter(name)
param.copy_(weight)
self.weight_transfer_engine.receive_weights(
typed_update_info,
load_weights=load_weights_direct,
)
self.weight_transfer_engine.receive_weights(
typed_update_info,
load_weights=load_weights_direct,
)
# NCCL broadcast/packed path are asynchronous.
# Sync here so the next step uses the new weights.
torch.accelerator.synchronize()
def finish_weight_update(self) -> None:
"""
Finish the current weight update.
For checkpoint format, this runs layerwise postprocessing.
Uses the is_checkpoint_format state stored by start_weight_update.
"""
self._check_weight_transfer_engine()
if not self._weight_update_active:
raise RuntimeError(
"start_weight_update must be called before finish_weight_update."
)
is_checkpoint_format = self._is_checkpoint_format
if is_checkpoint_format:
from vllm.model_executor.model_loader.reload import (
finalize_layerwise_reload,
)
model = self.model_runner.model
with torch.device(self.device):
finalize_layerwise_reload(model, self.model_config)
# Reset state
self._weight_update_active = False
self._is_checkpoint_format = True
def shutdown(self) -> None:
# has_kv_transfer_group can be None during interpreter shutdown.
if ensure_kv_transfer_shutdown is not None: