main.py 4.94 KB
Newer Older
chenych's avatar
chenych committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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.

import json
chenych's avatar
chenych committed
16
import torch
chenych's avatar
chenych committed
17
18
19
import ray
from omegaconf import OmegaConf

chenych's avatar
chenych committed
20
21
22
from ..single_controller.ray import RayWorkerGroup
from ..utils.tokenizer import get_processor, get_tokenizer
from ..workers.fsdp_workers import FSDPWorker
chenych's avatar
chenych committed
23
from ..workers.reward import BatchFunctionRewardManager, SequentialFunctionRewardManager
chenych's avatar
chenych committed
24
from .config import PPOConfig
chenych's avatar
update  
chenych committed
25
from .data_loader import create_dataloader
chenych's avatar
chenych committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from .ray_trainer import RayPPOTrainer, ResourcePoolManager, Role


# please make sure main_task is not scheduled on head
@ray.remote(num_cpus=1)
class Runner:
    """A runner for RL training."""

    def run(self, config: PPOConfig):
        # print config
        print(json.dumps(config.to_dict(), indent=2))

        # instantiate tokenizer
        tokenizer = get_tokenizer(
            config.worker.actor.model.model_path,
chenych's avatar
chenych committed
41
            override_chat_template=config.data.override_chat_template,
chenych's avatar
chenych committed
42
43
44
45
46
            trust_remote_code=config.worker.actor.model.trust_remote_code,
            use_fast=True,
        )
        processor = get_processor(
            config.worker.actor.model.model_path,
chenych's avatar
chenych committed
47
            override_chat_template=config.data.override_chat_template,
chenych's avatar
chenych committed
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
            trust_remote_code=config.worker.actor.model.trust_remote_code,
            use_fast=True,
        )

        # define worker classes
        ray_worker_group_cls = RayWorkerGroup
        role_worker_mapping = {
            Role.ActorRollout: ray.remote(FSDPWorker),
            Role.Critic: ray.remote(FSDPWorker),
            Role.RefPolicy: ray.remote(FSDPWorker),
        }
        global_pool_id = "global_pool"
        resource_pool_spec = {
            global_pool_id: [config.trainer.n_gpus_per_node] * config.trainer.nnodes,
        }
        mapping = {
            Role.ActorRollout: global_pool_id,
            Role.Critic: global_pool_id,
            Role.RefPolicy: global_pool_id,
        }
        resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping)

chenych's avatar
chenych committed
70
71
72
73
74
75
76
77
        if config.worker.reward.reward_type == "sequential":
            RewardManager = SequentialFunctionRewardManager
        elif config.worker.reward.reward_type == "batch":
            RewardManager = BatchFunctionRewardManager
        else:
            raise NotImplementedError(f"Unknown reward type {config.worker.reward.reward_type}.")

        RemoteRewardManager = ray.remote(RewardManager).options(num_cpus=config.worker.reward.num_cpus)
chenych's avatar
chenych committed
78
79
        reward_fn = RemoteRewardManager.remote(config.worker.reward, tokenizer)
        val_reward_fn = RemoteRewardManager.remote(config.worker.reward, tokenizer)
chenych's avatar
update  
chenych committed
80

chenych's avatar
chenych committed
81
        train_dataloader, val_dataloader = create_dataloader(config.data, tokenizer, processor)
chenych's avatar
chenych committed
82
83
84
85
86

        trainer = RayPPOTrainer(
            config=config,
            tokenizer=tokenizer,
            processor=processor,
chenych's avatar
update  
chenych committed
87
88
            train_dataloader=train_dataloader,
            val_dataloader=val_dataloader,
chenych's avatar
chenych committed
89
90
91
92
93
94
95
96
            role_worker_mapping=role_worker_mapping,
            resource_pool_manager=resource_pool_manager,
            ray_worker_group_cls=ray_worker_group_cls,
            reward_fn=reward_fn,
            val_reward_fn=val_reward_fn,
        )
        trainer.init_workers()
        trainer.fit()
chenych's avatar
chenych committed
97
98
99
100
101


def main():
    cli_args = OmegaConf.from_cli()
    default_config = OmegaConf.structured(PPOConfig())
chenych's avatar
chenych committed
102
103
104
105
106
107
108

    if hasattr(cli_args, "config"):
        config_path = cli_args.pop("config", None)
        file_config = OmegaConf.load(config_path)
        default_config = OmegaConf.merge(default_config, file_config)

    ppo_config = OmegaConf.merge(default_config, cli_args)
chenych's avatar
update  
chenych committed
109
110
    ppo_config: PPOConfig = OmegaConf.to_object(ppo_config)
    ppo_config.deep_post_init()
chenych's avatar
chenych committed
111
112

    if not ray.is_initialized():
chenych's avatar
update  
chenych committed
113
114
115
116
117
118
119
120
121
        runtime_env = {
            "env_vars": {
                "TOKENIZERS_PARALLELISM": "true",
                "NCCL_DEBUG": "WARN",
                "VLLM_LOGGING_LEVEL": "INFO",
                "TORCH_NCCL_AVOID_RECORD_STREAMS": "1",
                "PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:False",
            }
        }
chenych's avatar
Update  
chenych committed
122
        # this is for local ray cluster
chenych's avatar
chenych committed
123
124
        if torch.version.hip is not None:
            ray.init(num_gpus=torch.cuda.device_count(),
chenych's avatar
update  
chenych committed
125
126
                        ignore_reinit_error=True,
                        runtime_env=runtime_env)
chenych's avatar
chenych committed
127
        else:
chenych's avatar
update  
chenych committed
128
            ray.init(runtime_env=runtime_env)
chenych's avatar
chenych committed
129
130
    runner = Runner.remote()
    ray.get(runner.run.remote(ppo_config))
chenych's avatar
chenych committed
131
132
133
134


if __name__ == "__main__":
    main()