Save sharded weight checkpoints and enable safetensors format (#1058)
* Remove redundant log * First working version * Use constants from transformers and adjust debug logs * Minor * Fix update weights call on resume * Make it non breaking * Rename symbols
This commit is contained in:
@@ -19,7 +19,6 @@ confirm_cleanup() {
|
||||
echo " - **/rollouts"
|
||||
echo " - **/wandb"
|
||||
echo " - **/evals"
|
||||
echo " - **/evals"
|
||||
echo " - .pydantic_config"
|
||||
while true; do
|
||||
read -r -p "Proceed? [y/N]: " response
|
||||
|
||||
@@ -67,8 +67,7 @@ async def custom_run_server_worker(listen_address, sock, args, client_config=Non
|
||||
@app.post("/update_weights")
|
||||
async def _update_weights(request: Request):
|
||||
data = await request.json()
|
||||
model_path = data.get("model_path")
|
||||
await engine_client.collective_rpc("update_weights", args=(model_path,))
|
||||
await engine_client.collective_rpc("update_weights", args=(data.get("weight_dir"),))
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.post("/reload_weights")
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import torch
|
||||
from torch.nn import Module
|
||||
from vllm.model_executor.model_loader import DefaultModelLoader, get_model_loader
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
|
||||
# This is to get type hints for the Worker class but not actually extend it at runtime as this is required by vLLM worker extension
|
||||
if TYPE_CHECKING:
|
||||
from vllm.v1.worker.gpu_worker import Worker
|
||||
|
||||
Worker = Worker
|
||||
else:
|
||||
Worker = object
|
||||
|
||||
|
||||
class CheckpointWorker:
|
||||
class CheckpointWorker(Worker):
|
||||
"""
|
||||
This is an extension of a vLLM worker that allows for loading checkpoints
|
||||
from a specified directory via RPC calls from the AsyncLLMEngine class, exposed
|
||||
@@ -11,20 +21,26 @@ class CheckpointWorker:
|
||||
recent policy model from a checkpoint directory.
|
||||
"""
|
||||
|
||||
def update_weights(self, model_path: Path) -> None:
|
||||
def update_weights(self, weight_path: str) -> None:
|
||||
"""Update weights from a specified path pointing to a .pt file."""
|
||||
state_dict = torch.load(model_path, map_location="cpu", mmap=True)
|
||||
# Get vLLM model runner and model
|
||||
model_runner = self.model_runner
|
||||
model = model_runner.model
|
||||
assert isinstance(model, Module)
|
||||
|
||||
def weights_iterator():
|
||||
for key, value in state_dict.items():
|
||||
if not key:
|
||||
continue
|
||||
yield key, value
|
||||
|
||||
self.model_runner.model.load_weights(weights_iterator())
|
||||
# Get vLLM model loader
|
||||
model_loader = get_model_loader(self.load_config)
|
||||
assert isinstance(model_loader, DefaultModelLoader)
|
||||
local_source = DefaultModelLoader.Source(
|
||||
weight_path,
|
||||
revision=None, # TODO: Check that this is correct or if we should use the default (model_config.revision)
|
||||
prefix="",
|
||||
fall_back_to_pt=getattr(model, "fall_back_to_pt_during_load", True),
|
||||
allow_patterns_overrides=getattr(model, "allow_patterns_overrides", None),
|
||||
)
|
||||
weights_iterator = model_loader._get_weights_iterator(local_source)
|
||||
model.load_weights(weights_iterator) # type: ignore
|
||||
|
||||
# Process weights after loading (important for some models)
|
||||
from vllm.model_executor.model_loader.utils import process_weights_after_loading
|
||||
|
||||
device = next(self.model_runner.model.parameters()).device
|
||||
process_weights_after_loading(self.model_runner.model, self.model_runner.model_config, device)
|
||||
device = next(model.parameters()).device
|
||||
process_weights_after_loading(model, self.model_runner.model_config, device)
|
||||
|
||||
@@ -8,7 +8,6 @@ from openai import AsyncOpenAI, NotFoundError
|
||||
|
||||
from prime_rl.orchestrator.config import ClientConfig
|
||||
from prime_rl.utils.logger import get_logger
|
||||
from prime_rl.utils.utils import get_weight_ckpt_model_path
|
||||
|
||||
|
||||
def setup_client(client_config: ClientConfig) -> AsyncOpenAI:
|
||||
@@ -60,14 +59,13 @@ async def check_has_model(client: AsyncOpenAI, model_name: str) -> None:
|
||||
logger.debug(f"Model {model_name} was found in the inference pool")
|
||||
|
||||
|
||||
async def update_weights(client: AsyncOpenAI, path: Path, step: int) -> None:
|
||||
async def update_weights(client: AsyncOpenAI, weight_dir: Path) -> None:
|
||||
"""Make a HTTP post request to the vLLM server to update the weights."""
|
||||
logger = get_logger()
|
||||
url = str(client.base_url).strip()[:-4] + "/update_weights"
|
||||
try:
|
||||
model_path = get_weight_ckpt_model_path(path, step).absolute()
|
||||
logger.debug(f"Sending request to {url} to update weights from {model_path}")
|
||||
await client.post(url, cast_to=Response, body={"model_path": model_path.as_posix()})
|
||||
logger.debug(f"Sending request to {url} to update weights from {weight_dir}")
|
||||
await client.post(url, cast_to=Response, body={"weight_dir": weight_dir.as_posix()})
|
||||
except NotFoundError:
|
||||
logger.warning(f"The route {url} does not exist. Skipping weight update.")
|
||||
return
|
||||
|
||||
@@ -37,8 +37,10 @@ from prime_rl.utils.utils import (
|
||||
clean_exit,
|
||||
format_num,
|
||||
get_rollout_dir,
|
||||
get_step_path,
|
||||
get_weights_dir,
|
||||
to_col_format,
|
||||
wait_for_path,
|
||||
)
|
||||
import numpy as np
|
||||
|
||||
@@ -104,7 +106,7 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
logger.info(f"Resuming training from checkpoint step `{config.ckpt.resume_step}`")
|
||||
ckpt_manager.load(progress, buffer, step=config.ckpt.resume_step)
|
||||
ckpt_step = max(progress.step - config.async_level, 0)
|
||||
await update_weights(client, get_weights_dir(config.output_dir), ckpt_step)
|
||||
await update_weights(client, get_step_path(get_weights_dir(config.output_dir), ckpt_step))
|
||||
else:
|
||||
logger.info("Training from scratch. Resetting weights to base model")
|
||||
await reload_weights(client)
|
||||
@@ -151,14 +153,14 @@ async def orchestrate(config: OrchestratorConfig):
|
||||
ckpt_step = progress.step - config.async_level
|
||||
logger.info(f"Waiting for weight checkpoint {ckpt_step}")
|
||||
wait_for_weight_ckpt_start_time = time.time()
|
||||
wait_for_weight_checkpoint(get_weights_dir(config.output_dir), ckpt_step)
|
||||
wait_for_path(get_step_path(get_weights_dir(config.output_dir), ckpt_step) / "STABLE")
|
||||
wait_for_weight_ckpt_time = time.time() - wait_for_weight_ckpt_start_time
|
||||
logger.debug(f"Waited {wait_for_weight_ckpt_time:.2f}s for weight checkpoint")
|
||||
|
||||
# Update the weights
|
||||
logger.info(f"Updating weights to weight checkpoint {ckpt_step}")
|
||||
update_weights_start_time = time.time()
|
||||
await update_weights(client, get_weights_dir(config.output_dir), ckpt_step)
|
||||
await update_weights(client, get_step_path(get_weights_dir(config.output_dir), ckpt_step))
|
||||
update_weights_time = time.time() - update_weights_start_time
|
||||
logger.debug(f"Updated weights in {update_weights_time:.2f}s")
|
||||
|
||||
|
||||
@@ -371,6 +371,20 @@ class WeightCheckpointConfig(BaseConfig):
|
||||
),
|
||||
] = None
|
||||
|
||||
save_sharded: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
description="Whether to save the weight checkpoint in sharded format.",
|
||||
),
|
||||
] = False
|
||||
|
||||
save_format: Annotated[
|
||||
Literal["safetensors", "torch"],
|
||||
Field(
|
||||
description="The format to save the weight checkpoint in.",
|
||||
),
|
||||
] = "torch"
|
||||
|
||||
save_async: Annotated[
|
||||
bool,
|
||||
Field(
|
||||
|
||||
@@ -161,7 +161,13 @@ def train(config: RLTrainerConfig):
|
||||
save_weights_time = 0
|
||||
if progress.step > 0:
|
||||
save_weights_start_time = time.time()
|
||||
weight_ckpt_manager.save(model, tokenizer, step=progress.step)
|
||||
weight_ckpt_manager.save(
|
||||
model,
|
||||
tokenizer,
|
||||
save_format=config.weights.save_format,
|
||||
save_sharded=config.weights.save_sharded,
|
||||
step=progress.step,
|
||||
)
|
||||
save_weights_time = time.time() - save_weights_start_time
|
||||
|
||||
# Save the full checkpoint (if we are at an interval step and not at the first or last step)
|
||||
|
||||
@@ -144,7 +144,13 @@ def train(config: SFTTrainerConfig):
|
||||
):
|
||||
logger.info(f"Saving weight checkpoint at step {progress.step}")
|
||||
save_weights_start_time = time.time()
|
||||
weight_ckpt_manager.save(model, tokenizer, step=progress.step)
|
||||
weight_ckpt_manager.save(
|
||||
model,
|
||||
tokenizer,
|
||||
save_format=config.weights.save_format,
|
||||
save_sharded=config.weights.save_sharded,
|
||||
step=progress.step,
|
||||
)
|
||||
save_weights_time = time.time() - save_weights_start_time
|
||||
|
||||
# Save the full checkpoint (if we are at an interval step and not at the first or last step)
|
||||
@@ -349,8 +355,15 @@ def train(config: SFTTrainerConfig):
|
||||
|
||||
# Write final weight checkpoint
|
||||
if weight_ckpt_manager is not None:
|
||||
assert config.weights is not None
|
||||
logger.info("Writing final weight checkpoint")
|
||||
weight_ckpt_manager.save(model, tokenizer, step=progress.step)
|
||||
weight_ckpt_manager.save(
|
||||
model,
|
||||
tokenizer,
|
||||
save_format=config.weights.save_format,
|
||||
save_sharded=config.weights.save_sharded,
|
||||
step=progress.step,
|
||||
)
|
||||
|
||||
# Write final checkpoint
|
||||
if ckpt_manager is not None:
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
import json
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
import torch
|
||||
from huggingface_hub import split_torch_state_dict_into_shards
|
||||
from safetensors.torch import save_file
|
||||
from torch import Tensor, nn
|
||||
from torch.distributed.checkpoint.state_dict import _get_fqns as get_fqns
|
||||
from torch.distributed.tensor import DTensor
|
||||
from transformers.tokenization_utils import PreTrainedTokenizer
|
||||
from transformers.utils import SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_INDEX_NAME, WEIGHTS_NAME
|
||||
|
||||
from prime_rl.trainer.config import CheckpointConfig, LoRAConfig
|
||||
from prime_rl.trainer.lora import (
|
||||
@@ -119,32 +124,32 @@ class WeightCheckpointManager:
|
||||
|
||||
def _get_step_path(self, step: int) -> Path:
|
||||
return get_step_path(self.weights_dir, step)
|
||||
|
||||
|
||||
def _get_adapter_state_dict(self, model: nn.Module) -> dict[str, Tensor]:
|
||||
"""Get adapter weights with clean keys for PEFT compatibility."""
|
||||
lora_state = {}
|
||||
|
||||
|
||||
for key, value in model.state_dict().items():
|
||||
param = dict(model.named_parameters()).get(key)
|
||||
if param is None or not param.requires_grad:
|
||||
continue
|
||||
|
||||
|
||||
if isinstance(value, DTensor):
|
||||
value = value.full_tensor()
|
||||
|
||||
|
||||
if self._is_master:
|
||||
clean_key = next(iter(get_fqns(model, key)))
|
||||
clean_key = clean_key.replace(".base_layer.", ".")
|
||||
|
||||
|
||||
# Add PEFT-expected prefix
|
||||
peft_key = f"base_model.model.{clean_key}"
|
||||
|
||||
|
||||
# Add .weight suffix for LoRA parameters if missing
|
||||
if ("lora_A" in peft_key or "lora_B" in peft_key) and not peft_key.endswith(".weight"):
|
||||
peft_key = f"{peft_key}.weight"
|
||||
|
||||
|
||||
lora_state[peft_key] = value.to("cpu", non_blocking=False)
|
||||
|
||||
|
||||
torch.distributed.barrier()
|
||||
return lora_state
|
||||
|
||||
@@ -200,25 +205,85 @@ class WeightCheckpointManager:
|
||||
|
||||
return cpu_state
|
||||
|
||||
def _save_to_path(self, cpu_state: dict[str, Tensor], model: nn.Module, tokenizer: PreTrainedTokenizer, step: int):
|
||||
def _save_weights(
|
||||
self,
|
||||
state_dict: dict[str, Tensor],
|
||||
save_dir: Path,
|
||||
save_format: Literal["safetensors", "torch"],
|
||||
save_sharded: bool,
|
||||
):
|
||||
"""Utility function to save sharded weights to a directory. Inspired by `save_pretrained` from transformers."""
|
||||
weights_name = SAFE_WEIGHTS_NAME if save_format == "safetensors" else WEIGHTS_NAME
|
||||
if save_sharded:
|
||||
filename_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(
|
||||
".safetensors", "{suffix}.safetensors"
|
||||
)
|
||||
state_dict_split = split_torch_state_dict_into_shards(
|
||||
state_dict,
|
||||
filename_pattern=filename_pattern,
|
||||
)
|
||||
if state_dict_split.is_sharded:
|
||||
filenames = state_dict_split.filename_to_tensors.keys()
|
||||
self._logger.debug(f"Saving sharded weights to {len(filenames)} files: ({', '.join(filenames)})")
|
||||
else:
|
||||
self._logger.debug(f"Saving unsharded weights to {weights_name}")
|
||||
|
||||
# Save weights (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4252)
|
||||
filename_to_tensors = state_dict_split.filename_to_tensors.items()
|
||||
for shard_file, tensors in filename_to_tensors:
|
||||
shard = {}
|
||||
for tensor in tensors:
|
||||
assert isinstance(state_dict[tensor], Tensor)
|
||||
shard[tensor] = state_dict[tensor].contiguous()
|
||||
# delete reference, see https://github.com/huggingface/transformers/pull/34890
|
||||
del state_dict[tensor]
|
||||
if save_format == "safetensors":
|
||||
save_file(shard, save_dir / shard_file, metadata={"format": "pt"})
|
||||
else:
|
||||
torch.save(shard, save_dir / shard_file)
|
||||
del state_dict
|
||||
|
||||
# Save index (https://github.com/huggingface/transformers/blob/cd74917ffc3e8f84e4a886052c5ab32b7ac623cc/src/transformers/modeling_utils.py#L4301)
|
||||
if state_dict_split.is_sharded:
|
||||
index = {
|
||||
"metadata": {**state_dict_split.metadata},
|
||||
"weight_map": state_dict_split.tensor_to_filename,
|
||||
}
|
||||
save_index_file = SAFE_WEIGHTS_INDEX_NAME if save_format == "safetensors" else WEIGHTS_INDEX_NAME
|
||||
save_index_file = save_dir / save_index_file
|
||||
# Save the index as well
|
||||
with open(save_index_file, "w", encoding="utf-8") as f:
|
||||
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
|
||||
f.write(content)
|
||||
else:
|
||||
if save_format == "safetensors":
|
||||
save_file(state_dict, save_dir / weights_name, metadata={"format": "pt"})
|
||||
else:
|
||||
torch.save(state_dict, save_dir / weights_name)
|
||||
|
||||
def _save_to_path(
|
||||
self,
|
||||
state_dict: dict[str, Tensor],
|
||||
model,
|
||||
tokenizer,
|
||||
step: int,
|
||||
save_format: Literal["safetensors", "torch"],
|
||||
save_sharded: bool,
|
||||
):
|
||||
"""Save weight checkpoint for given step."""
|
||||
# Save weight checkpoint temporary dir to avoid race condition
|
||||
step_path = self._get_step_path(step)
|
||||
step_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self._logger.debug(f"Saving weight checkpoint to {step_path}")
|
||||
start_time = time.time()
|
||||
|
||||
# Suppress torch.distributed warnings during checkpoint saving
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", category=FutureWarning, module="torch.distributed")
|
||||
warnings.filterwarnings("ignore", category=UserWarning, module="torch.distributed.*")
|
||||
|
||||
# Save model weights to temporary file to avoid race condition
|
||||
model_path = self._get_model_path(step)
|
||||
tmp_model_path = model_path.with_suffix(".tmp")
|
||||
torch.save(cpu_state, tmp_model_path)
|
||||
# Rename temporary file to indicate checkpoint is complete
|
||||
tmp_model_path.rename(model_path)
|
||||
# Save weights
|
||||
self._save_weights(state_dict, step_path, save_format, save_sharded)
|
||||
|
||||
# Save model config, generation arguments and tokenizer
|
||||
model.config.save_pretrained(step_path)
|
||||
@@ -226,6 +291,7 @@ class WeightCheckpointManager:
|
||||
model.generation_config.save_pretrained(step_path)
|
||||
tokenizer.save_pretrained(step_path)
|
||||
|
||||
(step_path / "STABLE").touch() # Signal to the orchestrator that the weight checkpoint is ready
|
||||
self._logger.debug(f"Saved weight checkpoint to {step_path} in {time.time() - start_time:.2f} seconds")
|
||||
|
||||
def save(
|
||||
@@ -233,6 +299,8 @@ class WeightCheckpointManager:
|
||||
model: nn.Module,
|
||||
tokenizer: PreTrainedTokenizer,
|
||||
step: int,
|
||||
save_format: Literal["safetensors", "torch"],
|
||||
save_sharded: bool,
|
||||
dtype: torch.dtype = torch.bfloat16,
|
||||
):
|
||||
"""Save a HF-compatible weight-only checkpoint for a given step."""
|
||||
@@ -253,12 +321,12 @@ class WeightCheckpointManager:
|
||||
if self.config.save_async:
|
||||
thread = threading.Thread(
|
||||
target=self._save_to_path,
|
||||
args=(cpu_state, model, tokenizer, step),
|
||||
args=(cpu_state, model, tokenizer, step, save_format, save_sharded),
|
||||
name=f"weight-checkpoint-save-{step}",
|
||||
)
|
||||
thread.start()
|
||||
else:
|
||||
self._save_to_path(cpu_state, model, tokenizer, step)
|
||||
self._save_to_path(cpu_state, model, tokenizer, step, save_format, save_sharded)
|
||||
|
||||
return self._get_model_path(step)
|
||||
|
||||
@@ -307,7 +375,7 @@ def setup_weight_ckpt_manager(
|
||||
) -> WeightCheckpointManager | None:
|
||||
if weight_ckpt_config is None:
|
||||
return None
|
||||
|
||||
|
||||
return WeightCheckpointManager(
|
||||
output_dir, weight_ckpt_config, ckpt_config, async_level=async_level, lora_config=lora_config
|
||||
)
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user