support rl feature : weight checker (#51350)
Signed-off-by: shiyuan680 <yangcheng104@huawei.com> Signed-off-by: Ronald1995 <ronaldautomobile@163.com> Signed-off-by: aoshen02 <aoshen02@users.noreply.github.com> Co-authored-by: shiyuan680 <yangcheng104@huawei.com> Co-authored-by: Ronald1995 <ronaldautomobile@163.com> Co-authored-by: DeepSeek Harness <noreply@deepseek.com> Co-authored-by: aoshen02 <aoshen02@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: aoshen02 <aoshen@inferact.ai>
This commit is contained in:
co-authored by
shiyuan680
Ronald1995
DeepSeek Harness
aoshen02
Claude Opus 5.5
aoshen02
parent
a8e069f81b
commit
42d9f8ccdb
@@ -268,6 +268,10 @@ class EngineClient(ABC):
|
||||
"""Perform a collective RPC call to the given path."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def compute_weight_checksums(self) -> list[dict[str, str]]:
|
||||
"""Return rank-qualified weight digests from every worker of every engine."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def handle_fault(
|
||||
self, fault_tolerance_request: FaultToleranceRequest
|
||||
) -> FaultToleranceResult:
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
import json
|
||||
from http import HTTPStatus
|
||||
from typing import Annotated, Any
|
||||
from typing import Annotated, Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Body, FastAPI, HTTPException, Query, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
@@ -216,6 +216,43 @@ async def weight_info(raw_request: Request):
|
||||
return JSONResponse(content={"weight_version": weight_version})
|
||||
|
||||
|
||||
@router.post("/weight_checker")
|
||||
async def weight_checker(
|
||||
raw_request: Request,
|
||||
action: Annotated[Literal["checksum", "reset", "compare"], Body(embed=True)],
|
||||
baseline: Annotated[dict[str, str] | None, Body(embed=True)] = None,
|
||||
) -> JSONResponse:
|
||||
"""Checksum, reset, or compare model weights against a baseline."""
|
||||
client = engine_client(raw_request)
|
||||
if action == "reset":
|
||||
await client.collective_rpc("reset_weights")
|
||||
return JSONResponse(content={"status": "reset"})
|
||||
if action == "compare" and baseline is None:
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.BAD_REQUEST.value,
|
||||
detail="action='compare' requires a 'baseline' object",
|
||||
)
|
||||
|
||||
checksums: dict[str, str] = {}
|
||||
for worker_checksums in await client.compute_weight_checksums():
|
||||
if duplicates := checksums.keys() & worker_checksums.keys():
|
||||
raise HTTPException(
|
||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
|
||||
detail=f"Duplicate weight checksum keys: {sorted(duplicates)}",
|
||||
)
|
||||
checksums.update(worker_checksums)
|
||||
if action == "checksum":
|
||||
return JSONResponse(content={"checksums": checksums})
|
||||
|
||||
assert baseline is not None
|
||||
mismatches = sorted(
|
||||
key
|
||||
for key in checksums.keys() | baseline.keys()
|
||||
if checksums.get(key) != baseline.get(key)
|
||||
)
|
||||
return JSONResponse(content={"match": not mismatches, "mismatches": mismatches})
|
||||
|
||||
|
||||
@router.get("/get_world_size")
|
||||
async def get_world_size(
|
||||
raw_request: Request,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Per-parameter weight digests and reset, for verifying weight updates."""
|
||||
|
||||
import hashlib
|
||||
from collections.abc import Iterator
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils._python_dispatch import is_traceable_wrapper_subclass
|
||||
|
||||
from vllm.model_executor.parameter import SharedWeightParameter
|
||||
|
||||
|
||||
def _tensors(name: str, tensor: torch.Tensor) -> Iterator[tuple[str, torch.Tensor]]:
|
||||
# Both keep their bytes in inner tensors (e.g. TorchAO's qdata and scale).
|
||||
if isinstance(tensor, SharedWeightParameter):
|
||||
for index, partition in tensor.partitions.items():
|
||||
yield from _tensors(f"{name}.{index}", partition)
|
||||
elif is_traceable_wrapper_subclass(tensor):
|
||||
for attr in tensor.__tensor_flatten__()[0]:
|
||||
yield from _tensors(f"{name}.{attr}", getattr(tensor, attr))
|
||||
else:
|
||||
yield name, tensor
|
||||
|
||||
|
||||
def _weights(model: nn.Module) -> Iterator[tuple[str, torch.Tensor]]:
|
||||
for name, param in model.named_parameters():
|
||||
yield from _tensors(name, param)
|
||||
|
||||
|
||||
def compute_tensor_digests(model: nn.Module) -> dict[str, str]:
|
||||
return {
|
||||
name: hashlib.sha256(
|
||||
weight.detach().cpu().contiguous().view(-1).view(torch.uint8).numpy()
|
||||
).hexdigest()
|
||||
for name, weight in _weights(model)
|
||||
}
|
||||
|
||||
|
||||
def zero_weights(model: nn.Module) -> None:
|
||||
for _, weight in _weights(model):
|
||||
weight.data.zero_()
|
||||
@@ -1125,6 +1125,9 @@ class AsyncLLM(EngineClient):
|
||||
async def is_sleeping(self) -> bool:
|
||||
return await self.engine_core.is_sleeping_async()
|
||||
|
||||
async def compute_weight_checksums(self) -> list[dict[str, str]]:
|
||||
return await self.engine_core.compute_weight_checksums_async()
|
||||
|
||||
async def add_lora(self, lora_request: LoRARequest) -> bool:
|
||||
"""Load a new LoRA adapter into the engine for future requests."""
|
||||
return await self.engine_core.add_lora_async(lora_request)
|
||||
|
||||
@@ -1005,6 +1005,9 @@ class EngineCore:
|
||||
def execute_dummy_batch(self):
|
||||
self.model_executor.execute_dummy_batch()
|
||||
|
||||
def compute_weight_checksums(self) -> list[dict[str, str]]:
|
||||
return self.collective_rpc("compute_weight_checksums")
|
||||
|
||||
def add_lora(self, lora_request: LoRARequest) -> bool:
|
||||
return self.model_executor.add_lora(lora_request)
|
||||
|
||||
|
||||
@@ -1362,6 +1362,10 @@ class AsyncMPClient(MPClient):
|
||||
"collective_rpc", method, timeout, args, kwargs
|
||||
)
|
||||
|
||||
async def compute_weight_checksums_async(self) -> list[dict[str, str]]:
|
||||
per_engine = await self.call_utility_all_async("compute_weight_checksums")
|
||||
return [worker for workers in per_engine for worker in workers]
|
||||
|
||||
async def handle_fault(
|
||||
self, ft_request: FaultToleranceRequest
|
||||
) -> FaultToleranceResult:
|
||||
|
||||
@@ -58,6 +58,10 @@ from vllm.distributed.weight_transfer import (
|
||||
from vllm.logger import init_logger
|
||||
from vllm.lora.request import LoRARequest
|
||||
from vllm.model_executor.model_loader import get_model_loader
|
||||
from vllm.model_executor.model_loader.weight_checksum import (
|
||||
compute_tensor_digests,
|
||||
zero_weights,
|
||||
)
|
||||
from vllm.model_executor.warmup.kernel_warmup import kernel_warmup
|
||||
from vllm.multimodal.gpu_ipc_memory import reserve_mm_ipc_gpu_memory
|
||||
from vllm.platforms import current_platform
|
||||
@@ -342,6 +346,22 @@ class Worker(WorkerBase):
|
||||
def checkpoint_restore(self) -> None:
|
||||
checkpoint_restore_distributed_state()
|
||||
|
||||
def _weight_checksum_prefix(self) -> str:
|
||||
# data_parallel_rank is 0 in dense workers; only the index is unique.
|
||||
dp = self.parallel_config.data_parallel_index
|
||||
pp = get_pp_group().rank_in_group
|
||||
pcp = get_pcp_group().rank_in_group
|
||||
tp = get_tp_group().rank_in_group
|
||||
return f"dp{dp}:pp{pp}:pcp{pcp}:tp{tp}:"
|
||||
|
||||
def compute_weight_checksums(self) -> dict[str, str]:
|
||||
prefix = self._weight_checksum_prefix()
|
||||
digests = compute_tensor_digests(self.model_runner.get_model())
|
||||
return {prefix + name: digest for name, digest in digests.items()}
|
||||
|
||||
def reset_weights(self) -> None:
|
||||
zero_weights(self.model_runner.get_model())
|
||||
|
||||
def _maybe_get_memory_pool_context(self, tag: str) -> AbstractContextManager:
|
||||
if (
|
||||
current_platform.is_cuda_alike()
|
||||
|
||||
Reference in New Issue
Block a user