Home > Technology peripherals > AI > Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

王林
Release: 2023-05-11 15:28:11
forward
1037 people have browsed it

OpenRL is a PyTorch-based reinforcement learning research framework developed by the Fourth Paradigm reinforcement learning team. It supports the training of single-agent, multi-agent, natural language and other tasks. OpenRL is developed based on PyTorch, with the goal of providing the reinforcement learning research community with an easy-to-use, flexible, efficient, and sustainably scalable platform. Currently, the features supported by OpenRL include:

  • ##A common interface that is easy to use and supports single-agent and multi-agent training
  • Supports reinforcement learning training for natural language tasks (such as dialogue tasks)
  • Supports importing models and data from Hugging Face
  • Supports LSTM, GRU, Transformer and other models
  • Support a variety of training acceleration, such as: automatic mixed precision training, half-precision policy network data collection, etc.
  • Support User-defined training model, reward model, training data and environment
  • Support gymnasium environment
  • Support dictionary observation space
  • Support mainstream training visualization tools such as wandb and tensorboardX
  • Support serial and parallel training in the environment while ensuring consistent training effects in both modes
  • Chinese and English documentation
  • Provide unit testing and code coverage testing
  • Conform to Black Code Style and type checking

Currently, OpenRL is open source on GitHub:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

Project address: https ://github.com/OpenRL-Lab/openrl

First experience with OpenRL

OpenRL can currently be installed through pip:

<code>pip install openrl</code>
Copy after login

can also be installed through conda:

<code>conda install -c openrl openrl</code>
Copy after login

OpenRL provides a simple and easy-to-use interface for entry-level users of reinforcement learning. The following is a CartPole environment trained using the PPO algorithm. Example:

<code># train_ppo.pyfrom openrl.envs.common import makefrom openrl.modules.common import PPONet as Netfrom openrl.runners.common import PPOAgent as Agentenv = make ("CartPole-v1", env_num=9) # 创建环境,并设置环境并行数为 9net = Net (env) # 创建神经网络agent = Agent (net) # 初始化智能体agent.train (total_time_steps=20000) # 开始训练,并设置环境运行总步数为 20000</code>
Copy after login

Using OpenRL to train an agent only requires four simple steps: Create environment=> Initialize model=> Initialize agent=> Start training!

Execute the above code on an ordinary laptop, and it only takes a few seconds to complete the training of the agent:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.


In addition, OpenRL also provides the same simple and easy-to-use interface for the training of multi-agent, natural language and other tasks. For example, for the MPE environment in multi-agent tasks, OpenRL only needs to call a few lines of code to complete the training:

<code># train_ppo.pyfrom openrl.envs.common import makefrom openrl.modules.common import PPONet as Netfrom openrl.runners.common import PPOAgent as Agentdef train ():# 创建 MPE 环境,使用异步环境,即每个智能体独立运行env = make ("simple_spread",env_num=100,asynchrnotallow=True,)# 创建 神经网络,使用 GPU 进行训练net = Net (env, device="cuda")agent = Agent (net) # 初始化训练器# 开始训练agent.train (total_time_steps=5000000)# 保存训练完成的智能体agent.save ("./ppo_agent/")if __name__ == "__main__":train ()</code>
Copy after login

The following figure shows the performance of the agent before and after training through OpenRL :

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

Load configuration file

In addition, OpenRL also supports loading from the command line and configuration files. The training parameters are modified. For example, users can quickly modify the learning rate during training by executing python train_ppo.py --lr 5e-4.

When there are many configuration parameters, OpenRL also supports users to write their own configuration files to modify training parameters. For example, the user can create the following configuration file (mpe_ppo.yaml) and modify the parameters in it:

<code># mpe_ppo.yamlseed: 0 # 设置 seed,保证每次实验结果一致lr: 7e-4 # 设置学习率episode_length: 25 # 设置每个 episode 的长度use_recurrent_policy: true # 设置是否使用 RNNuse_joint_action_loss: true # 设置是否使用 JRPO 算法use_valuenorm: true # 设置是否使用 value normalization</code>
Copy after login

Finally, the user only needs to specify the configuration file when executing the program. :

<code>python train_ppo.py --config mpe_ppo.yaml</code>
Copy after login

训练与测试可视化

此外,通过 OpenRL,用户还可以方便地使用 wandb 来可视化训练过程:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

OpenRL 还提供了各种环境可视化的接口,方便用户对并行环境进行可视化。用户可以在创建并行环境的时候设置环境的渲染模式为 "group_human",便可以同时对多个并行环境进行可视化:

<code>env = make ("simple_spread", env_num=9, render_mode="group_human")</code>
Copy after login

此外,用户还可以通过引入 GIFWrapper 来把环境运行过程保存为 gif 动画:

<code>from openrl.envs.wrappers import GIFWrapperenv = GIFWrapper (env, "test_simple_spread.gif")</code>
Copy after login

智能体的保存和加载

OpenRL 提供 agent.save () 和 agent.load () 接口来保存和加载训练好的智能体,并通过 agent.act () 接口来获取测试时的智能体动作:

<code># test_ppo.pyfrom openrl.envs.common import makefrom openrl.modules.common import PPONet as Netfrom openrl.runners.common import PPOAgent as Agentfrom openrl.envs.wrappers import GIFWrapper # 用于生成 gifdef test ():# 创建 MPE 环境env = make ( "simple_spread", env_num=4)# 使用 GIFWrapper,用于生成 gifenv = GIFWrapper (env, "test_simple_spread.gif")agent = Agent (Net (env)) # 创建 智能体# 保存智能体agent.save ("./ppo_agent/")# 加载智能体agent.load ('./ppo_agent/')# 开始测试obs, _ = env.reset ()while True:# 智能体根据 observation 预测下一个动作action, _ = agent.act (obs)obs, r, done, info = env.step (action)if done.any ():breakenv.close ()if __name__ == "__main__":test ()</code>
Copy after login

执行该测试代码,便可以在同级目录下找到保存好的环境运行动画文件 (test_simple_spread.gif):

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

训练自然语言对话任务

最近的研究表明,强化学习也可以用于训练语言模型, 并且能显著提升模型的性能。目前,OpenRL 已经支持自然语言对话任务的强化学习训练。OpenRL 通过模块化设计,支持用户加载自己的数据集 ,自定义训练模型,自定义奖励模型,自定义 wandb 信息输出以及一键开启混合精度训练等。

对于对话任务训练,OpenRL 提供了同样简单易用的训练接口:

<code># train_ppo.pyfrom openrl.envs.common import makefrom openrl.modules.common import PPONet as Netfrom openrl.runners.common import PPOAgent as Agentfrom openrl.configs.config import create_config_parserdef train ():# 添加读取配置文件的代码cfg_parser = create_config_parser ()cfg = cfg_parser.parse_args ()# 创建 NLP 环境env = make ("daily_dialog",env_num=2,asynchrnotallow=True,cfg=cfg,)net = Net (env, cfg=cfg, device="cuda")agent = Agent (net)agent.train (total_time_steps=5000000)if __name__ == "__main__":train ()</code>
Copy after login

可以看出,OpenRL 训练对话任务和其他强化学习任务一样,都是通过创建交互环境的方式进行训练。

加载自定义数据集

训练对话任务,需要对话数据集。这里我们可以使用 Hugging Face 上的公开数据集(用户可以替换成自己的数据集)。加载数据集,只需要在配置文件中传入数据集的名称或者路径即可:

<code># nlp_ppo.yamldata_path: daily_dialog # 数据集路径env: # 环境所用到的参数args: {'tokenizer_path': 'gpt2'} # 读取 tokenizer 的路径seed: 0 # 设置 seed,保证每次实验结果一致lr: 1e-6 # 设置 policy 模型的学习率critic_lr: 1e-6 # 设置 critic 模型的学习率episode_length: 20 # 设置每个 episode 的长度use_recurrent_policy: true</code>
Copy after login

上述配置文件中的 data_path 可以设置为 Hugging Face 数据集名称或者本地数据集路径。此外,环境参数中的 tokenizer_path 用于指定加载文字编码器的 Hugging Face 名称或者本地路径。

自定义训练模型

在 OpenRL 中,我们可以使用 Hugging Face 上的模型来进行训练。为了加载 Hugging Face 上的模型,我们首先需要在配置文件 nlp_ppo.yaml 中添加以下内容:

<code># nlp_ppo.yaml# 预训练模型路径model_path: rajkumarrrk/gpt2-fine-tuned-on-daily-dialog use_share_model: true # 策略网络和价值网络是否共享模型ppo_epoch: 5 # ppo 训练迭代次数data_path: daily_dialog # 数据集名称或者路径env: # 环境所用到的参数args: {'tokenizer_path': 'gpt2'} # 读取 tokenizer 的路径lr: 1e-6 # 设置 policy 模型的学习率critic_lr: 1e-6 # 设置 critic 模型的学习率episode_length: 128 # 设置每个 episode 的长度num_mini_batch: 20</code>
Copy after login

然后在 train_ppo.py 中添加以下代码:

<code># train_ppo.pyfrom openrl.envs.common import makefrom openrl.modules.common import PPONet as Netfrom openrl.runners.common import PPOAgent as Agentfrom openrl.configs.config import create_config_parserfrom openrl.modules.networks.policy_value_network_gpt import (PolicyValueNetworkGPT as PolicyValueNetwork,)def train ():# 添加读取配置文件的代码cfg_parser = create_config_parser ()cfg = cfg_parser.parse_args ()# 创建 NLP 环境env = make ("daily_dialog",env_num=2,asynchrnotallow=True,cfg=cfg,)# 创建自定义神经网络model_dict = {"model": PolicyValueNetwork}net = Net (env, cfg=cfg, model_dict=model_dict)# 创建训练智能体agent = Agent (net)agent.train (total_time_steps=5000000)if __name__ == "__main__":train ()</code>
Copy after login

通过以上简单几行的修改,用户便可以使用 Hugging Face 上的预训练模型进行训练。如果用户希望分别自定义策略网络和价值网络,可以写好 CustomPolicyNetwork 以及 CustomValueNetwork 后通过以下方式从外部传入训练网络:

<code>model_dict = {"policy": CustomPolicyNetwork,"critic": CustomValueNetwork,}net = Net (env, model_dict=model_dict)</code>
Copy after login

自定义奖励模型

通常,自然语言任务的数据集中并不包含奖励信息。因此,如果需要使用强化学习来训练自然语言任务,就需要使用额外的奖励模型来生成奖励。在该对话任务中,我们可以使用一个复合的奖励模型,它包含以下三个部分:

●意图奖励:即当智能体生成的语句和期望的意图接近时,智能体便可以获得更高的奖励。

●METEOR 指标奖励:METEOR 是一个用于评估文本生成质量的指标,它可以用来衡量生成的语句和期望的语句的相似程度。我们把这个指标作为奖励反馈给智能体,以达到优化生成的语句的效果。

●KL 散度奖励:该奖励用来限制智能体生成的文本偏离预训练模型的程度,防止出现 reward hacking 的问题。

我们最终的奖励为以上三个奖励的加权和,其中 KL 散度奖励的系数是随着 KL 散度的大小动态变化的。想在 OpenRL 中使用该奖励模型,用户无需修改训练代码,只需要在 nlp_ppo.yaml 文件中添加 reward_class 参数即可:

<code># nlp_ppo.yamlreward_class:id: NLPReward # 奖励模型名称args: {# 用于意图判断的模型的名称或路径"intent_model": rajkumarrrk/roberta-daily-dialog-intent-classifier,# 用于计算 KL 散度的预训练模型的名称或路径"ref_model": roberta-base, # 用于意图判断的 tokenizer 的名称或路径}</code>
Copy after login

OpenRL 支持用户使用自定义的奖励模型。首先,用户需要编写自定义奖励模型 (需要继承 BaseReward 类)。接着,用户需要注册自定义的奖励模型,即在 train_ppo.py 添加以下代码:

<code># train_ppo.pyfrom openrl.rewards.nlp_reward import CustomRewardfrom openrl.rewards import RewardFactoryRewardFactory.register ("CustomReward", CustomReward)</code>
Copy after login

最后,用户只需要在配置文件中填写自定义的奖励模型即可:

<code>reward_class:id: "CustomReward" # 自定义奖励模型名称args: {} # 用户自定义奖励函数可能用到的参数</code>
Copy after login

自定义训练过程信息输出

OpenRL 还支持用户自定义 wandb 和 tensorboard 的输出内容。例如,在该任务的训练过程中,我们还需要输出各种类型奖励的信息和 KL 散度系数的信息, 用户可以在 nlp_ppo.yaml 文件中加入 vec_info_class 参数来实现:

<code># nlp_ppo.yamlvec_info_class:id: "NLPVecInfo" # 调用 NLPVecInfo 类以打印 NLP 任务中奖励函数的信息# 设置 wandb 信息wandb_entity: openrl # 这里用于指定 wandb 团队名称,请把 openrl 替换为你自己的团队名称experiment_name: train_nlp # 这里用于指定实验名称run_dir: ./run_results/ # 这里用于指定实验数据保存的路径log_interval: 1 # 这里用于指定每隔多少个 episode 上传一次 wandb 数据# 自行填写其他参数...</code>
Copy after login

修改完配置文件后,在 train_ppo.py 文件中启用 wandb:

<code># train_ppo.pyagent.train (total_time_steps=100000, use_wandb=True)</code>
Copy after login

然后执行 python train_ppo.py –config nlp_ppo.yaml,稍后,便可以在 wandb 中看到如下的输出:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

从上图可以看到,wandb 输出了各种类型奖励的信息和 KL 散度系数的信息。 

如果用户还需要输出其他信息,还可以参考 NLPVecInfo 类 和 VecInfo 类来实现自己的 CustomVecInfo 类。然后,需要在 train_ppo.py 中注册自定义的 CustomVecInfo 类:

<code># train_ppo.py # 注册自定义输出信息类 VecInfoFactory.register ("CustomVecInfo", CustomVecInfo)</code>
Copy after login

最后,只需要在 nlp_ppo.yaml 中填写 CustomVecInfo 类即可启用:

<code># nlp_ppo.yamlvec_info_class:id: "CustomVecInfo" # 调用自定义 CustomVecInfo 类以输出自定义信息</code>
Copy after login

使用混合精度训练加速

OpenRL 还提供了一键开启混合精度训练的功能。用户只需要在配置文件中加入以下参数即可:

<code># nlp_ppo.yamluse_amp: true # 开启混合精度训练</code>
Copy after login

对比评测

下表格展示了使用 OpenRL 训练该对话任务的结果。结果显示使用强化学习训练后,模型各项指标皆有所提升。另外,从下表可以看出,相较于 RL4LMs , OpenRL 的训练速度更快(在同样 3090 显卡的机器上,速度提升 17% ),最终的性能指标也更好:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

最后,对于训练好的智能体,用户可以方便地通过 agent.chat () 接口进行对话:

<code># chat.pyfrom openrl.runners.common import ChatAgent as Agentdef chat ():agent = Agent.load ("./ppo_agent", tokenizer="gpt2",)history = []print ("Welcome to OpenRL!")while True:input_text = input ("> User:")if input_text == "quit":breakelif input_text == "reset":history = []print ("Welcome to OpenRL!")continueresponse = agent.chat (input_text, history)print (f"> OpenRL Agent: {response}")history.append (input_text)history.append (response)if __name__ == "__main__":chat ()</code>
Copy after login

执行 python chat.py ,便可以和训练好的智能体进行对话了:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

总结

OpenRL 框架经过了 OpenRL-Lab 的多次迭代并应用于学术研究和 AI 竞赛,目前已经成为了一个较为成熟的强化学习框架。OpenRL-Lab 团队将持续维护和更新 OpenRL,欢迎大家加入我们的开源社区,一起为强化学习的发展做出贡献。更多关于 OpenRL 的信息,可以参考:

  • OpenRL 官方仓库:https://github.com/OpenRL-Lab/openrl/
  • OpenRL 中文文档:https://openrl-docs.readthedocs.io/zh/latest/

致谢

OpenRL 框架的开发吸取了其他强化学习框架的优点:

  • Stable-baselines3: https://github.com/DLR-RM/stable-baselines3
  • ##pytorch-a2c-ppo-acktr-gail: https://github.com/ikostrikov/pytorch-a2c-ppo-acktr-gail
  • MAPPO: https://github.com/marlbenchmark/on-policy
  • Gymnasium: https://github.com/Farama-Foundation/Gymnasium
  • DI-engine: https://github.com/opendilab/DI -engine/
  • ##Tianshou: https://github.com/thu-ml/tianshou
  • ##RL4LMs: https://github. com/allenai/RL4LMs
  • Future work

Currently, OpenRL is still in the continuous development and construction stage. In the future, OpenRL will open source more functions:

Support agent self-game training
  • Add offline reinforcement learning, model learning, and inverse reinforcement learning algorithms
  • Add more reinforcement learning environments and algorithms
  • Integrate acceleration frameworks such as Deepspeed
  • Support multi-machine distributed training
  • OpenRL Lab Team

The OpenRL framework is developed by the OpenRL Lab team, which is the reinforcement learning research team under 4Paradigm. Fourth Paradigm has long been committed to the research, development and industrial application of reinforcement learning. In order to promote the integration of industry, academia and research in reinforcement learning, 4Paradigm established the OpenRL Lab research team, with the goal of open source advanced technology and frontier exploration of artificial intelligence. Less than a year after its establishment, the OpenRL Lab team has published three papers in AAMAS, participated in the Google Football Game 11 vs 11 competition and won third place. The TiZero agent proposed by the team is the first to complete the training of Google Football full-field game agent from scratch through curriculum learning, distributed reinforcement learning, self-gaming and other technologies:

Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.

As of October 28, 2022, Tizero ranked first on the Jidi evaluation platform:

The above is the detailed content of Training speed is increased by 17%. The fourth paradigm open source reinforcement learning research framework supports single and multi-agent training.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template