【資料圖】
機器之心專欄
作者:第四范式強化學習團隊
強化學習研究框架 OpenRL 是基于 PyTorch 開發的,已經在 GitHub 上開源。
pip install openrl
conda install -c openrl openrl
# train_ppo.py
from openrl.envs.common import make
from openrl.modules.common import PPONet as Net
from openrl.runners.common import PPOAgent as Agent
env = make ("CartPole-v1", env_num=9) # 創建環境,并設置環境并行數為 9
net = Net (env) # 創建神經網絡
agent = Agent (net) # 初始化智能體
agent.train (total_time_steps=20000) # 開始訓練,并設置環境運行總步數為 20000
# train_ppo.py
from openrl.envs.common import make
from openrl.modules.common import PPONet as Net
from openrl.runners.common import PPOAgent as Agent
def train ():
# 創建 MPE 環境,使用異步環境,即每個智能體獨立運行
env = make (
"simple_spread",
env_num=100,
asynchronous=True,
)
# 創建 神經網絡,使用 GPU 進行訓練
net = Net (env, device="cuda")
agent = Agent (net) # 初始化訓練器
# 開始訓練
agent.train (total_time_steps=5000000)
# 保存訓練完成的智能體
agent.save ("./ppo_agent/")
if __name__ == "__main__":
train ()
# mpe_ppo.yaml
seed: 0 # 設置 seed,保證每次實驗結果一致
lr: 7e-4 # 設置學習率
episode_length: 25 # 設置每個 episode 的長度
use_recurrent_policy: true # 設置是否使用 RNN
use_joint_action_loss: true # 設置是否使用 JRPO 算法
use_valuenorm: true # 設置是否使用 value normalization
python train_ppo.py --config mpe_ppo.yaml
env = make ("simple_spread", env_num=9, render_mode="group_human")
from openrl.envs.wrappers import GIFWrapper
env = GIFWrapper (env, "test_simple_spread.gif")
# test_ppo.py
from openrl.envs.common import make
from openrl.modules.common import PPONet as Net
from openrl.runners.common import PPOAgent as Agent
from openrl.envs.wrappers import GIFWrapper # 用于生成 gif
def test ():
# 創建 MPE 環境
env = make ( "simple_spread", env_num=4)
# 使用 GIFWrapper,用于生成 gif
env = 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 ():
break
env.close ()
if __name__ == "__main__":
test ()
# train_ppo.py
from openrl.envs.common import make
from openrl.modules.common import PPONet as Net
from openrl.runners.common import PPOAgent as Agent
from openrl.configs.config import create_config_parser
def train ():
# 添加讀取配置文件的代碼
cfg_parser = create_config_parser ()
cfg = cfg_parser.parse_args ()
# 創建 NLP 環境
env = make ("daily_dialog",env_num=2,asynchronous=True,cfg=cfg,)
net = Net (env, cfg=cfg, device="cuda")
agent = Agent (net)
agent.train (total_time_steps=5000000)
if __name__ == "__main__":
train ()
# nlp_ppo.yaml
data_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
# 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
# train_ppo.py
from openrl.envs.common import make
from openrl.modules.common import PPONet as Net
from openrl.runners.common import PPOAgent as Agent
from openrl.configs.config import create_config_parser
from 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,asynchronous=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 ()
model_dict = {
"policy":CustomPolicyNetwork,
"critic":CustomValueNetwork,
}
net = Net (env, model_dict=model_dict)
# nlp_ppo.yaml
reward_class:
id: NLPReward # 獎勵模型名稱
args: {
# 用于意圖判斷的模型的名稱或路徑
"intent_model": rajkumarrrk/roberta-daily-dialog-intent-classifier,
# 用于計算 KL 散度的預訓練模型的名稱或路徑
"ref_model": roberta-base, # 用于意圖判斷的 tokenizer 的名稱或路徑
}
# train_ppo.py
fromopenrl.rewards.nlp_rewardimportCustomReward
from openrl.rewards import RewardFactory
RewardFactory.register("CustomReward",CustomReward)
reward_class:
id:"CustomReward"#自定義獎勵模型名稱
args: {} # 用戶自定義獎勵函數可能用到的參數
# nlp_ppo.yaml
vec_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 數據
# 自行填寫其他參數...
# train_ppo.py
agent.train (total_time_steps=100000, use_wandb=True)
# train_ppo.py # 注冊自定義輸出信息類
VecInfoFactory.register("CustomVecInfo",CustomVecInfo)
# nlp_ppo.yaml
vec_info_class:
id:"CustomVecInfo"#調用自定義CustomVecInfo類以輸出自定義信息
# nlp_ppo.yaml
use_amp: true # 開啟混合精度訓練
# chat.py
from openrl.runners.common import ChatAgent as Agent
def chat ():
agent = Agent.load ("./ppo_agent", tokenizer="gpt2",)
history = []
print ("Welcome to OpenRL!")
while True:
input_text = input ("> User:")
if input_text == "quit":
break
elif input_text == "reset":
history = []
print ("Welcome to OpenRL!")
continue
response = agent.chat (input_text, history)
print (f"> OpenRL Agent: {response}")
history.append (input_text)
history.append (response)
if __name__ == "__main__":
chat ()
OpenRL框架是由OpenRL Lab團隊開發,該團隊是第四范式公司旗下的強化學習研究團隊。第四范式長期致力于強化學習的研發和工業應用。為了促進強化學習的產學研一體化,第四范式成立了OpenRL Lab研究團隊,目標是先進技術開源和人工智能前沿探索。成立不到一年,OpenRL Lab團隊已經在AAMAS發表過三篇論文,參加谷歌足球游戲 11 vs 11比賽并獲得第三的成績。團隊提出的TiZero智能體,實現了首個從零開始,通過課程學習、分布式強化學習、自博弈等技術完成谷歌足球全場游戲智能體的訓練:
?THE END
轉載請聯系本公眾號獲得授權
投稿或尋求報道:content@jiqizhixin.com
Copyright @ 2015-2022 海外生活網版權所有 備案號: 滬ICP備2020036824號-21 聯系郵箱:562 66 29@qq.com