mirror of
https://github.com/volcengine/verl.git
synced 2025-10-20 21:53:50 +08:00
As initially mentioned in https://github.com/volcengine/verl/discussions/1941, having structured configuration classes in verl makes argument passing easier for testing and validation. This is an extended thread on the current implementation of configuration schema in verl. Related PRs: - https://github.com/volcengine/verl/pull/2117 - https://github.com/volcengine/verl/pull/2621 # Motivation By moving from loose `omegaconfig.DictConfig`-based parameters to structured dataclasses, we gain: - Type safety & IDE support when accessing fields (e.g. cfg.optim.lr). - Validation hooks via __post_init__ in each class. - Immutable defaults with controlled mutability (e.g., an extra field). - Seamless Hydra/OmegaConf integration and easy per-recipe extension. # Core: BaseConfig hydra natively provides support for converting DictConfig to dataclass, but dataclass does not support accessing attribute via `get()`. We introduce a base class to provide backward compatibility and make the change less abrupt for existing users. All config dataclasses inherit from BaseConfig, which: - Implements collections.abc.Mapping → dict-like iteration/access. - Freezes attributes once set, unless listed in _mutable_fields. - Provides an `extra: dict[str, Any]` for unchecked extensions. ```python @dataclass class BaseConfig(collections.abc.Mapping): """Dict-like, frozen dataclass with opt-in mutability.""" _mutable_fields: set[str] = {"extra"} extra: dict[str, Any] = field(default_factory=dict) def __setattr__(self, name: str, value): if name in self.__dict__ and name not in self._mutable_fields: raise FrozenInstanceError(f"Field '{name}' is frozen") super().__setattr__(name, value) # Mapping methods: get, __getitem__, __iter__, __len__ … ``` # Example Config Classes (verl/trainer/config) Each sub-component of the trainer has its own dataclass, inheriting BaseConfig. ```yaml: critic: checkpoint: _target_: verl.trainer.config.CheckpointConfig save_contents: ["model","optimizer","extra"] load_contents: ["model","optimizer","extra"] async_save: false ``` Definition: ```python @dataclass class CheckpointConfig(BaseConfig): """What to save/load and async behavior.""" save_contents: list[str] = field(default_factory=lambda: ["model","optimizer","extra"]) load_contents: list[str] = field(default_factory=lambda: ["model","optimizer","extra"]) async_save: bool = False def __post_init__(self): # validation checks go here after initialization ckpt_cfg = CheckpointConfig(async_save=True) print(ckpt_cfg.save_contents) print(ckpt_cfg.get("save_contents", default_value)) print(ckpt_cfg["save_contents"]) # converting hydra-generated omegaconf.DictConfig to the dataclass config: from verl.utils.config import omegaconf_to_dataclass ckpt_cfg_from_cli = omegaconf_to_dataclass(config.critic.checkpoint) ``` # Extending existing config classes Because now configs become structured, unexpected keys would raise exceptions. To add new keys, there are two ways: ## Explicit class extensions: ```python from verl.workers.config import FSDPActorConfig @dataclass class SPPOActorConfig(FSDPActorConfig): """Add SPPO-specific temperature/penalty.""" sppo_eta: float = 1.0 ``` When using yaml or from command line, update the target config class: ```yaml hydra: searchpath: - file://verl/trainer/config defaults: - ppo_trainer # base trainer config - _self_ # then apply these overrides actor_rollout_ref: actor: _target_: recipe.sppo.config.SPPOActorConfig # **new target dataclass required for extension ** sppo_eta: 1.0 ``` or directly from command line: ```bash python main_sppo.py \ actor_rollout_ref.actor._target_=recipe.sppo.config.SPPOActorConfig \ actor_rollout_ref.actor.sppo_eta=1.0 ``` ## Leverage the `extra` field Adding more keys to the `extra` field of any dataclass that inherits from `BaseConfig` also works. This way there's no need to define your own dataclass in python: ```yaml hydra: searchpath: - file://verl/trainer/config defaults: - ppo_trainer # base trainer config - _self_ # then apply these overrides actor_rollout_ref: actor: extra: sppo_eta: 1.0 ``` # Declaring mutable fields For historical reasons some fields in the configs are mutated inplace in the codebase such as batch size for data/sequence parallelism. We are in the process of deprecating this kind of behavior. However, if you want to intentionally mutate one field, specify it with the `_mutable_fields` attr: ```python @dataclass class CheckpointConfig(BaseConfig): """What to save/load and async behavior.""" _mutable_fields = BaseConfig._mutable_fields | {"save_contents"} # mark save_contents as mutable. save_contents: list[str] = field(default_factory=lambda: ["model","optimizer","extra"]) load_contents: list[str] = field(default_factory=lambda: ["model","optimizer","extra"]) async_save: bool = False ``` # Other helpful resources verl default trainer configs combines the following config files together, specified in the `_defaults_` field: https://github.com/volcengine/verl/blob/main/verl/trainer/config/ppo_trainer.yaml#L1-L36 - verl/trainer/config/ppo_trainer.yaml # main config for entrypoint - verl/trainer/config/actor/dp_actor.yaml - verl/trainer/config/critic/dp_critic.yaml - verl/trainer/config/reward_model/dp_reward_model.yaml - verl/trainer/config/rollout/rollout.yaml To quickly peek the default full config in a single file, you can check the auto-generated full config in https://github.com/volcengine/verl/blob/main/verl/trainer/config/_generated_ppo_trainer.yaml # Change log and impact on existing code This PR converts the following fields to structured dataclass in the training pipeline. More can be done in future PRs (contributions from the community is welcome) - [x] actor_rollout_ref.actor - [x] critic - [ ] actor_rollout_ref.rollout - [ ] actor_rollout_ref.ref - [ ] reward_model - [ ] data - [ ] trainer Changes needed for existing code that added new fields to config: - see recipe/sppo for an example - `OmegaConf.to_container(self.config.model.get("override_config", OmegaConf.create()))` now has to manually changed to `self.config.model.get("override_config", {})`. Because OmegaConf.to_container expects a DictConfig but config.model.override_config is already a dict. # Other Breaking Changes critic.optim.lr for megatron changed from 1e-6 to 1e-5 --------- Signed-off-by: ShareLer <ShareLe@163.com> Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Joel <wuxibin@bytedance.com> Co-authored-by: Cheetah <1659275352@qq.com> Co-authored-by: 杨睿 <yangruipis@163.com> Co-authored-by: X. HU <huxiaobo@zju.edu.cn> Co-authored-by: Le Xue <48175490+ShareLer@users.noreply.github.com> Co-authored-by: Ziheng Jiang <ziheng@apache.org> Co-authored-by: Blue Space <57280232+ETOgaosion@users.noreply.github.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
139 lines
5.0 KiB
Python
139 lines
5.0 KiB
Python
# Copyright 2024 Bytedance Ltd. and/or its affiliates
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
"""
|
|
Compare vLLM AsyncLLM backend: ExternalRayDistributedExecutor(remote call) vs RayDistributedExecutor(compiled graph)
|
|
|
|
1. Prepare openai/gsm8k dataset
|
|
python3 examples/data_preprocess/gsm8k.py
|
|
|
|
2. Run perf test
|
|
python3 tests/workers/rollout/perf/vllm_async_rollout.py >perf.log 2>&1
|
|
|
|
hardware: Nvidia 8*H20
|
|
packages:
|
|
- torch==2.6.0
|
|
- vllm==0.8.5
|
|
|
|
[DEBUG] backend: sync, n_gpus_per_node: 8, batch_size: 2048, step: 0, step_time: 21.27 secs
|
|
[DEBUG] backend: zeromq, n_gpus_per_node: 8, batch_size: 2048, step: 0, step_time: 23.40 secs
|
|
[DEBUG] backend: ray, n_gpus_per_node: 8, batch_size: 2048, step: 0, step_time: 25.33 secs
|
|
"""
|
|
|
|
import os
|
|
import time
|
|
|
|
import ray
|
|
from omegaconf import DictConfig
|
|
from torch.utils.data import SequentialSampler
|
|
from torchdata.stateful_dataloader import StatefulDataLoader
|
|
|
|
from tests.experimental.agent_loop.agent_utils import AgentLoopManager, RayWorkerGroup, init_agent_loop_manager
|
|
from verl.protocol import DataProto
|
|
from verl.utils import hf_tokenizer
|
|
from verl.utils.dataset import RLHFDataset
|
|
from verl.utils.dataset.rl_dataset import collate_fn as default_collate_fn
|
|
|
|
|
|
def init_config(n_gpus_per_node) -> DictConfig:
|
|
import os
|
|
|
|
from hydra import compose, initialize_config_dir
|
|
|
|
with initialize_config_dir(config_dir=os.path.abspath("verl/trainer/config")):
|
|
config = compose(
|
|
config_name="ppo_trainer",
|
|
overrides=[
|
|
"actor_rollout_ref.actor.use_dynamic_bsz=true",
|
|
"actor_rollout_ref.actor.fsdp_config.param_offload=True",
|
|
"actor_rollout_ref.actor.fsdp_config.optimizer_offload=True",
|
|
],
|
|
)
|
|
config.trainer.n_gpus_per_node = n_gpus_per_node
|
|
config.data.train_batch_size = 128
|
|
config.data.return_raw_chat = True
|
|
config.actor_rollout_ref.model.path = "Qwen/Qwen2.5-7B-Instruct"
|
|
config.actor_rollout_ref.rollout.mode = "async"
|
|
config.actor_rollout_ref.rollout.tensor_model_parallel_size = 2
|
|
config.actor_rollout_ref.rollout.gpu_memory_utilization = 0.9
|
|
config.actor_rollout_ref.rollout.multi_turn.format = "hermes"
|
|
config.actor_rollout_ref.rollout.prompt_length = 4096
|
|
config.actor_rollout_ref.rollout.response_length = 4096
|
|
config.actor_rollout_ref.rollout.n = 16
|
|
|
|
return config
|
|
|
|
|
|
def initialize(config, backend) -> tuple[AgentLoopManager | RayWorkerGroup, StatefulDataLoader]:
|
|
env_vars = {
|
|
"NCCL_DEBUG": "WARN",
|
|
"VLLM_USE_V1": "1",
|
|
"VERL_VLLM_DISTRIBUTED_BACKEND": backend,
|
|
}
|
|
ray.init(runtime_env={"env_vars": env_vars})
|
|
|
|
# STEP 1: init async llm server
|
|
server = init_agent_loop_manager(config)
|
|
|
|
# STEP 2: create dataloader
|
|
tokenizer = hf_tokenizer(config.actor_rollout_ref.model.path)
|
|
dataset = RLHFDataset(
|
|
data_files=os.path.expanduser("~/data/gsm8k/train.parquet"),
|
|
tokenizer=tokenizer,
|
|
config=config.data,
|
|
)
|
|
dataloader = StatefulDataLoader(
|
|
dataset=dataset,
|
|
batch_size=config.data.get("gen_batch_size", config.data.train_batch_size),
|
|
num_workers=config.data.get("dataloader_num_workers", 8),
|
|
drop_last=True,
|
|
collate_fn=default_collate_fn,
|
|
sampler=SequentialSampler(dataset),
|
|
)
|
|
|
|
return server, dataloader
|
|
|
|
|
|
def perf_rollout(mode, backend, n_gpus_per_node, num_steps):
|
|
config = init_config(n_gpus_per_node)
|
|
config.actor_rollout_ref.rollout.mode = mode
|
|
agent_loop_manager, dataloader = initialize(config, backend)
|
|
|
|
for step, batch in enumerate(dataloader):
|
|
batch: DataProto = DataProto.from_single_dict(batch)
|
|
batch = batch.pop(
|
|
batch_keys=["input_ids", "attention_mask", "position_ids"],
|
|
non_tensor_batch_keys=["raw_prompt_ids", "raw_prompt"],
|
|
)
|
|
t_start = time.time()
|
|
gen_batch = agent_loop_manager.generate_sequences(batch)
|
|
t_end = time.time()
|
|
print(
|
|
f"[DEBUG] backend: {backend}, n_gpus_per_node: {n_gpus_per_node}, batch_size: {len(gen_batch)}, "
|
|
f"step: {step}, step_time: {t_end - t_start:.2f} secs"
|
|
)
|
|
if step + 1 >= num_steps:
|
|
break
|
|
|
|
ray.shutdown()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
num_steps = 1
|
|
n_gpus_per_node = 8
|
|
|
|
# test_cases = [("sync", "sync"), ("async", "zeromq"), ("async", "ray")]
|
|
test_cases = [("async", "zeromq"), ("async", "ray")]
|
|
for mode, backend in test_cases:
|
|
perf_rollout(mode=mode, backend=backend, n_gpus_per_node=n_gpus_per_node, num_steps=num_steps)
|